首先,我在这个网站上搜索了很多,并找到了关于这个主题的其他帖子,甚至是我正在做的同一个作业,所以代码非常相似……但是,有一些地方略有不同。我正在学习这门课程,使用“从 Python 开始,第 4 版”,我的作业来自第 5 章“15. 测试平均和成绩”。我已经为除了输入验证之外的所有内容编写了代码,我的导师坚持我们使用这些代码,尽管我们只应该使用本书迄今为止涵盖的编码技术:没有列表、元组、字典、lambda 等。 . 这使得我在网上(和本网站)找到的大多数用于输入验证的示例都没用,因为我无法弄清楚它们,如果我想的话也无法使用它们。我已经向讲师寻求帮助(在线课程),但是已经好几个星期没有收到任何回复了,所以我来了。该程序应该要求用户输入 5 个测试分数,找到分数的平均值,为每个分数分配一个字母等级,然后显示分数和字母等级以及平均值。我认为如果我使用“for score in range(1, 6)”循环来询问分数,验证输入会更容易,但是我不知道如何访问用户输入的每个分数以发送到确定_等级函数,然后在主函数中显示(我没有包含下面的任何代码)......所以我最终为每个分数创建了一个变量,但后来我遇到了如何验证输入的问题(确保输入的分数不小于 0 或大于 100,或者用户为每个变量输入了数字而不是字母)。一世' 我希望能够在代码中编写一些异常处理,这样如果用户输入的是字母而不是数字,则不会抛出异常,因为我的老师说过“从现在开始,我的工作是尝试使您的程序,”尽管他还没有回复我到底如何实现这种输入验证。任何帮助都将不胜感激,我已经为此苦苦挣扎了好几天,这让我感到非常紧张。
编辑:TypeError: input_validation() 缺少 4 个必需的位置参数:'score2'、'score3'、'score4' 和 'score5' 是我得到的错误,我知道我做错了什么,但是,我不不知道是什么......我觉得有一种更简单的方法来处理多个变量的输入验证..因为我在这方面仍然很陌生,所以我不知道如何实现它。
def get_scores():
score1 = input_validation(float(input('Enter the score for the first test: ')))
score2 = input_validation(float(input('Enter the score for the second test: ')))
score3 = input_validation(float(input('Enter the score for the third test: ')))
score4 = input_validation(float(input('Enter the score for the fourth test: ')))
score5 = input_validation(float(input('Enter the score for the fifth test: ')))
return score1, score2, score3, score4, score5
def input_validation(score1, score2, score3, score4, score5):
while (score1, score2, score3, score4, score5) < 0 or (score1, score2, score3, score4, score5) > 100:
print('Score cannot be less than 0 or greater than 100!')
(score1, score2, score3, score4, score5) = float(input('Please enter a correct test score: '))
return score1, score2, score3, score4, score5
您的直接错误是您已定义input_validation()
为采用五个参数,但在调用它时只传递了一个参数。
在一个函数中收集输入并在另一个函数中验证输入是很尴尬的,因为这些函数必须非常紧密地协调以允许重新提示错误输入。
一次要求几个分数然后同时验证它们也很尴尬,因为如果有些分数有效而有些无效,你会怎么做?您要么必须再次询问所有分数,这会浪费用户的时间,或者您需要一种仅针对无效分数重新提示的方法,这是不必要的复杂性。
一次只处理一个分数可能是一个更好的设计,所有的输入和验证都在一个地方:
def input_validation(prompt):
# keep looping until they enter a good score
while True:
# get the answer as a string
answer = input(prompt)
try:
# convert to float
score = float(answer)
# if in range, we're done! return the converted score number
if 0 <= score <= 100:
return score
# otherwise out of range, print an error message and keep looping
else:
print('Score cannot be less than 0 or greater than 100!')
# if the answer wasn't a number, print an error message and keep looping
except ValueError:
print ('That is not a test score.')
然后你可以这样称呼它:
score1 = input_validation('Enter the score for the first test: ')
score2 = input_validation('Enter the score for the second test: ')
如果您想将分数保存在列表中而不是有五个单独的变量:
scores = []
for i in range(5):
scores.append(input_validation('Enter the score for test number %d: ' % i+1))
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句