Python 3x中的if / else语句

时间:2018-09-13 20:42:12

标签: python python-3.x if-statement

我对编程和Python很陌生。首先,我正在开发一个小游戏,它将要求用户输入一些信息,然后对其进行“某些操作”。 我的问题是,我似乎已经在考虑用户输入的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!")

1 个答案:

答案 0 :(得分:1)

这样的事情怎么样?

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

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