Python 3x 中的 if/else 语句



我对编程和Python很陌生。首先,我正在开发一个小游戏,它将要求用户输入一些内容,然后用它做"一些事情"。我的问题是我似乎已经考虑到用户输入的 int 是否低于或高于我的参数,但我似乎找不到一种方法来重新提示用户,如果他们输入的任何东西而不是 int。

以我有限的知识,我认为在使用 if/elif/else 语句时,如果您没有定义 if/elif 正在寻找的内容,那么 else 语句是否存在您没有考虑的其他所有内容?

寻找有关如何掌握这一基本概念的更多见解

提前谢谢你!

prompt = True
while prompt == True:
user_input = input("Please give me a number that is greater than 0 but less than 10 n >")
if  user_input > 0 and user_input <= 10:
print("Good job " + str(user_input)  +  " is a great number")
break
elif (user_input  > 10):
print("Hey dummy " + str(user_input) + " is greater than 10")
elif (user_input  <= 0):
print("Hey dummy " + str(user_input) + " is less than 0")
else:
print("I have no idea what you typed, try again!")

这样的事情怎么样?

a = -1 
while a < 0 or a > 10:
try:
a = int(input("Enter a number between 0 and 10: "))
except ValueError:
continue

这将仅允许用户输入从010int,如果数字超出此范围,这也将消除打印这些消息的需要,如果您想保留这些消息,我可以进行调整并向您展示如何处理

最新更新