5

我已经设置了以下 for 循环来接受 5 个测试分数。我希望循环提示用户输入 5 个不同的分数。现在我可以通过编写输入“请输入您的下一个测试分数”来做到这一点,但我宁愿让每个输入的分数提示其相关数字。

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

Traceback (most recent call last):
  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
4

2 回答 2

8

一种简单(且正确!)的方式来编写您想要的内容:

score = int(input('Please enter your score for test ' + str(y) + ': '))
于 2012-04-02T02:54:38.457 回答
2

因为只需要一个参数而您提供了三个参数input 因此期望它神奇地将它们连接在一起:-)

您需要做的是将您的三部分字符串构建到一个参数中,例如:

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

这就是 Python 进行sprintf-type 字符串构造的方式。举例来说,

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

是一种将这三个表达式转换为一个字符串的方法"42 / 7 = 6"

有关其工作原理的说明,请参见此处。您还可以使用此处显示的更灵活的方法,可按如下方式使用:

input("Please enter your score for test {0}: ".format(y))
于 2012-04-02T01:17:38.107 回答