如何将pythons对int(input('Q1')中字符串输入的响应更改为循环Q?

2024-05-13 02:36:02 发布

您现在位置:Python中文网/ 问答频道 /正文

我的问题是,例如,当我打字时

x = int(input('whats 1+1')

如果有人开玩笑地键入一个字符串,例如'two'或'2'python auto crash,有没有办法让python自动崩溃,告诉此人将其输入为整数,然后使用while循环,重复这个问题,直到他们这样做。thnx提前:)

顺便说一句,输入变量(x)时必须是整数


Tags: 字符串autoinput键入整数crashinttwo
2条回答
def get_int(prompt="Enter an Integer:"):
    while True:
        try:
           return int(input(prompt))
        except ValueError:
           print("That is not an integer!")

x = get_int("What is 1+1")
def get_integer():  # Define a function to make things easier
    while True:  # Keep looping, until we return from the function
        x = input('What is 1 + 1?')  # ask for input
        try:
            x = int(x)  # can we convert it to an integer?
        except (ValueError, TypeError):  # None or 'hello' would fail
            print('Invalid entry, please try again!')
        else:  # no exception!
            print('x was good!')
            return x  # exit our function

value = get_integer()  # Call our function

相关问题 更多 >