2012-02-23 61 views
2

所以我在Python中有一行代码,我不断收到错误信息。代码 线:Python中的参数错误

input("This is your", movecounter, "move, type the number you want to move north") 

1号线只是import random

错误:

File "<stdin>", line 1, in <module> 
    File "<stdin>", line 12, in berries 
TypeError: input expected at most 1 arguments, got 3 

我该如何解决这个问题?我没有看到任何参数?

+0

请了投票的正确答案,并从以下4,所有的选择答案获胜是正确的,你提供的信息。 – 2012-02-23 20:54:55

回答

4

至少,你想用逗号替换逗号,并调用movecounter(我猜测是一个整数)str

input("This is your " + str(movecounter) + 
    " move, type the number you want to move north") 

参数之间用逗号隔开,所以你实际上是给input三个参数。

做的更Python的方式是使用str.format

input("This is your {0:d} move, type the number you want to move north".format(
    movecounter)) 

你也可以使用旧式% formatting operator通过Kimvais的建议,但我建议学习和使用str.format。它被取代并改进了旧的%运算符,最终将被弃用。许多人仍然使用它。

+0

使用'+'而不是某种形式的模板来创建字符串是脆弱的和非惯用的,所以实际上没有多少理由可以显示它。 (顺便说一下,这段代码中的反斜杠是没有必要的。) 另外,我不知道有计划曾经弃用'%'字符串格式 - 如果有的话,为什么要等待? – 2012-02-23 19:26:30

+0

@Mike我为了完整而展示它;我想说明OP如何在使用他试图使用的“方法”的同时使其工作。我编辑了答案,强调它不是一个好的解决方案。关于'%'的弃用,让我引用[python 3.0中有什么新东西](http://docs.python.org/release/3.0.1/whatsnew/3.0.html):“*该计划是[。 ..]开始在Python 3.1中弃用%运算符。*“。等待是因为,正如我所指出的那样,*许多人仍在使用它*。 – 2012-02-24 09:07:38

+0

谢谢你指出。 “将来会贬低”的想法对我来说似乎还真是太奇怪了,因为弃用并没有实际做任何事情。只要您意识到计划最终要删除某些内容,似乎应立即废弃。在Python 3.2和3.3的开发版本上打开警告级别后,它看起来像'str .__ mod__'尚未开始发出弃用警告。 – 2012-02-24 13:01:53

2

你可能想要的是input("This is your %d move, type the number you wat to move north" % movecounter)

使用,连接字符串仅适用于print,所以最好避免它 - 即使是在打印。

0

逗号用于对函数input()进行参数传递,因此给出了输入三个参数。如果你想创建一个单一的字符串,你不能使用逗号。

input_string = "This is your" + movecounter + "move, type the number you want to move north" 
input(input_string) 
0

该错误说错了参数里面的input()函数。 input()可以有0或1个参数,你给他们3个参数。

要解决此问题,请将1参数提供给input()。和python3更适当的方式向前是使用format()

input("This is your {} move, type the number you want to move north".format(movecounter))