python - 输入验证有问题/排除最高值/最低值
问题描述
我对编程非常、非常、非常陌生。到目前为止,我真的很喜欢这门课。然而,最近编程挑战有点令人困惑和令人生畏。我面临的最新挑战让我摸不着头脑,因为我在书本和网上都找不到帮助。简而言之,我需要创建一个程序,在 0-10 范围内获取五位评委的分数,排除给出的最高和最低分数,然后计算剩余三个分数的平均值。虽然我了解如何验证单个值的用户输入并计算平均值,但我不知道如何验证所有 5 个输入的用户输入而不做任何太繁琐的事情,并排除用户输入的最高分和最低分。我知道我需要做什么。将用户输入作为浮点数,然后将其传输到一个获取最高和最低分数的函数,然后将其发送到另一个计算平均值的函数。如果有人可以帮助我解决这个问题,我将不胜感激。以下是我到目前为止所做的工作。先感谢您。
def getJudgeData():
badEntry = True
while (badEntry) :
judge1 = float (input("Please enter the first judge's score : "))
if (judge1 < 0 or judge1 > 10) :
print ("The score must be greater than 0 and less than or equal to 10!")
else:
badEntry = False
while (badEntry) :
judge2 = float (input("Please enter the second judge's score : "))
if (judge2 < 0 or judge2 > 10) :
print ("The score must be greater than 0 and less than or equal to 10!")
else:
badEntry = False
解决方案
下面的代码将要求输入 5 次分数,这就是为什么循环在 5 范围内的原因。如果用户输入的不是整数,它将抛出一个值错误。如果要浮动,可以将其更改为浮动。如果用户输入超过10个,它会提示用户输入正确范围内的数字。然后,calculate_average 函数返回四舍五入到小数点后两位的平均值,如果需要更多或更少的小数位,您可以更改它。
我不确定你减去最大值和最小值是什么意思,所以我从分数中删除了。但如果我误解了,就把它们留在那儿,然后照常计算平均值。
scores = []
def getJudgeData():
for i in range(5):
try:
judge_score = int(input("Please enter the first judge's score : "))
if (judge_score in range(11)):
scores.append(judge_score)
else:
print('Enter a score from 1 to 10')
except ValueError:
print("Enter a valid number")
def calculate_average():
max_value = max(scores)
min_value = min(scores)
scores.remove(max_value)
scores.remove(min_value)
average = sum(scores)/len(scores)
return round(average, 2)
getJudgeData()
print(calculate_average())
推荐阅读
- c# - 在 Startup.cs 中使用 .AddGoogle() 时如何在 Web 应用中构建 GmailService?
- metamask - Metamask 无法在私有仲裁区块链中执行正常交易
- c# - 如何正确使用 FileStream.ReadAsync 不阻塞 UI
- c++ - 使用 aruco 和 opencv4 的未解析符号
- python - 与条件函数组合,用于组合 Python 中的每 2 个元素
- c# - Emgu imagebox停靠在面板中,当映射更大的图像时,即使滚动到右下角,图像的某些部分也不会显示
- node.js - 具有 Lambda 集成的无服务器响应模板
- javascript - 将回车转换为换行符 - 正则表达式
- html - 在 Bootstrap 右侧制作按钮
- python - Python 中的货币符号奇怪。相同的代码,不同的系统,不同的结果为什么?