英文:
Elif statement skipped
问题
while True:
top_of_range = input("输入一个1-10之间的数字: ")
if top_of_range.isdigit():
top_of_range = int(top_of_range)
break
elif top_of_range.isdigit() and int(top_of_range) <= 0:
print("请输入大于0的数字。")
continue
else:
print("请输入一个数字。")
continue
如果我输入一个小于等于0的值,它会直接跳到"请输入一个数字。",期望它显示"请输入大于0的数字。"并回到输入。
英文:
while True:
top_of_range = input("Type a number from 1-10: ")
if top_of_range.isdigit():
top_of_range = int(top_of_range)
break
elif top_of_range.isdigit():
int(top_of_range) <= 0
print("Please type a number larger than 0.")
continue
else:
print("Please type a number.")
continue
if I type a value <= 0 , It just bypasses to "Please type a number."
Expecting it to show "Please type a number larger than 0." and loop back to the input.
答案1
得分: 1
请记住,只有if/elif/else的一个分支实际上会被评估。您可能也希望尝试将输入转换为整数,并在需要时处理异常。
通过在输入不在范围内时引发ValueError
,您可以同时处理这两种错误。
英文:
Keep in mind that only one branch of an if/elif/else can actually be evaluated. You may also wish to simply try to convert input to int, and handle the exception if needed.
By raising ValueError
on the input not being in range, you can handle both errors at the same time.
def get_number_in_range(bot, top):
while True:
try:
n = int(input(f"Type a number from {bot}-{top}: "))
if n < bot or n > top: raise ValueError
return n
except ValueError:
print("Please type a valid number.")
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论