以十进制形式验证用户输入

问题描述 投票:0回答:1

我需要将用户输入验证为小数。我的程序需要确保输入学分的学生在 1-4.5 的范围内输入它们,0 表示“退出”,并且无法让我的尝试工作。我已经尝试根据列表和范围验证输入,当我同时执行这两个操作时,我会遇到有趣的错误。

list[1, 1.0, 1.5, 2, 2.0, 2.5, 3, 3.0, 3.5, 4, 4.0, 4.5]

credits = input('Enter the credits for the course. Enter 0 to quit.')

if credits in list:
     total = total + credits
     MAX = MAX + 1
else:
     print('You have entered an invalid number. The number of credits')
     print('must be between 1 and 4.5.')
     number = float(input(f'Enter the credits for Course {MAX} and Term, or enter 0 to exit:'))
     total = total + credits
     MAX = MAX + 1

我也试过了

credits = (1, 4.5)
python validation range decimal
1个回答
0
投票

为什么不使用:

total = 0
MAX = 0

credits = float(input('Enter the credits for the course. Enter 0 to quit.'))

if credits >= 1.0 and credits <= 4.5:
     total = total + credits
     MAX = MAX + 1
else:
     print('You have entered an invalid number. The number of credits')
     print('must be between 1 and 4.5.')
     number = float(input(f'Enter the credits for Course {MAX} and Term, or enter 0 to exit:'))
     total = total + credits
     MAX = MAX + 1

显然,将

total
MAX
值编辑为您想要的值。

这将检查输入的值是否在 1 和 4.5 之间,如果不正确,它将移至 else 语句。

© www.soinside.com 2019 - 2024. All rights reserved.