我试图让这个简单的代码只接受来自(0,100)的整数和数字。我不想使用循环来验证我的输入,并希望它们仅以"无效输入"退出。我坚持使用这个部分,因为当我没有有效的输入时,我似乎无法退出而没有(" Letter等级:")部分...当我输入字母时,该消息不会出现。
这是我到目前为止所做的事情......我是初学者,所以如果有人可以帮助我,那就太好了。)
def convert_grade_to_letter(number_grade):
letter_grade = ''
if number_grade >= 90 and number_grade <= 100:
letter_grade = 'A'
elif number_grade >= 80:
letter_grade = 'B'
elif number_grade >= 70:
letter_grade = 'C'
elif number_grade >= 60:
letter_grade = 'D'
elif number_grade < 60 and number_grade >= 0:
letter_grade = 'F'
else:
print("invalid input")
return letter_grade
def main():
number_grade = int(input("Input number grade: "))
letter_grade = convert_grade_to_letter(number_grade)
print("Letter grade: " + letter_grade)
main()
答案 0 :(得分:0)
考虑捕获ValueError
异常以验证您的成绩,包括整数验证和0-100范围验证:
try:
number_grade = int(input("Input number grade: "))
is_valid = 0 <= number_grade <= 100
if not is_valid:
raise ValueError("Number grade is not in the 0-100 range.")
letter_grade = convert_grade_to_letter(number_grade)
print("Letter grade: " + letter_grade)
except ValueError:
print("Could not parse grade")
答案 1 :(得分:0)
在循环中清理输入是要走的路。这样,您只能为您的功能提供正确的数据(始终清理用户输入 - 它们太有创意):
def convert_grade_to_letter(number_grade):
letter_grade = ''
if number_grade >= 90: # not needed: and number_grade <= 100:
letter_grade = 'A'
elif number_grade >= 80:
letter_grade = 'B'
elif number_grade >= 70:
letter_grade = 'C'
elif number_grade >= 60:
letter_grade = 'D'
else: # not needed: - if number_grade < 60 and number_grade >= 0:
letter_grade = 'F'
return letter_grade
def main():
while True: # loop until the value is between 0 and 100 and a valid int
try:
number_grade = int(input("Input number grade: "))
if 0 < number_grade <= 100:
break
except ValueError:
print("Invalid Input - 1 to 100 allowed")
letter_grade = convert_grade_to_letter(number_grade)
print("Letter grade: " + letter_grade)
main()
如果不使用循环是一些不完整的限制,返回一个指示器,允许程序检查解析是否成功:
def convert_grade_to_letter(number_grade):
letter_grade = ''
if number_grade >= 90 and number_grade <= 100:
letter_grade = 'A'
elif number_grade >= 80:
letter_grade = 'B'
elif number_grade >= 70:
letter_grade = 'C'
elif number_grade >= 60:
letter_grade = 'D'
elif number_grade < 60 and number_grade >= 0:
letter_grade = 'F'
else:
print("invalid input")
return None # check for None, only print if not None
return letter_grade
def main():
number_grade = int(input("Input number grade: "))
letter_grade = convert_grade_to_letter(number_grade)
if letter_grade is not None:
print("Letter grade: " + letter_grade)
main()