2012-04-02 255 views
2

我设置了以下循环以接受5个测试分数。我想循环提示用户输入5个不同的分数。现在我可以通过编写输入“请输入你的下一个测试分数”来做到这一点,但我宁愿让每个输入的分数都提示它的相关数字。错误 - 最多输入1个参数的输入,得到3

因此,对于第一次输入,我希望它显示“请输入测试1的分数”,然后为第二个分数显示“请输入测试2的分数”。当我尝试运行这个循环中,我得到以下错误:

回溯(最近通话最后一个):

File "C:/Python32/Assignment 7.2", line 35, in <module> 

main() 

File "C:/Python32/Assignment 7.2", line 30, in main 

scores = input_scores() 

File "C:/Python32/Assignment 7.2", line 5, in input_scores 

score = int(input('Please enter your score for test', y,' : ')) 

TypeError: input expected at most 1 arguments, got 3 

下面的代码

def input_scores(): 
scores = [] 
y = 1 
for num in range(5): 
    score = int(input('Please enter your score for test', y,': ')) 

    while score < 0 or score > 100: 
     print ('Error --- all test scores must be between 0 and 100 points') 
     score = int(input('Please try again: ')) 
    scores.append(score) 
    y += 1 
    return scores 

非常感谢你的帮助:) 〜Dustin

回答

4

一个简单的(!和正确的)的方式来写你想要什么:

score = int(input('Please enter your score for test ' + str(y) + ': ')) 
2

因为input确实只想要一个参数,并且您提供三个,期待它神奇地连接在一起:-)

什么,你需要做的是建立自己的三部分组成的字符串成一个参数,比如用:

input("Please enter your score for test %d: " % y) 

这是Python中如何做sprintf型串建设。举例来说,

"%d/%d = %d" % (42, 7, 42/7) 

是采取这些三个表达式,并把它们变成一个字符串"42/7 = 6"的方式。请参阅here以了解其工作原理您还可以使用here所示的更灵活的方法,该方法可以使用如下:

input("Please enter your score for test {0}: ".format(y)) 
+0

哈哈我看到了我在我输入之后做了。我就像“哦,也许就是这样。”我把它当作打印功能来对待。虽然我要查找你刚做的那件漂亮的东西,但我不确定它是如何工作的 – 2012-04-02 01:22:49

+0

@Dustin,http://docs.python.org/library/stdtypes.html#string-formatting,但你可以也可以使用更具适应性的'{}'方法:http://docs.python.org/tutorial/inputoutput.html。我会将其添加到答案中。 – paxdiablo 2012-04-02 01:27:03