【问题标题】:Error - input expected at most 1 argument, got 3错误 - 最多输入 1 个参数,得到 3 个
【发布时间】:2012-04-15 17:23:32
【问题描述】:

我设置了以下 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

【问题讨论】:

    标签: python arguments traceback


    【解决方案1】:

    因为input 确实只需要一个参数,而您提供了三个参数,希望它能神奇地将它们结合在一起:-)

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

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

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

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

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

    请参阅here 了解其工作原理。也可以使用here所示的更灵活的方法,可以如下使用:

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

    【讨论】:

    【解决方案2】:

    一个简单(而且正确!)的方式来写你想要的:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-08-01
      • 1970-01-01
      • 2022-11-17
      • 2023-03-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多