繁体   English   中英

我需要输入是一个数字。 如果不是,则显示“请输入数字”并再次要求输入

[英]I need the input to be a number. If nor, display “please enter number” and ask for input again

这就是我想要的,但对于整数。 我不允许使用breakcontinue退出循环。

# basically I need this, but with an int(input('please enter a number'))

ask = input('Would you like to play Steal or Deal [y|n]? ')


while ask not in ('y', 'n'):

    print ("Please enter either 'y' or 'n'")
    print('')
    ask = input('Would you like to play Steal or Deal [y|n]? ')

您可以尝试将字符串转换为 int 并捕获异常:

def is_number(s):
    try:
        int(s)
        return True
    except ValueError:
        return False

ask = input('please enter a number: ')

while not is_number(ask):

    print ("no, a number!")
    print('')
    ask = input('please enter a number: ')

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM