Python - User input data type

前端 未结 3 950
我在风中等你
我在风中等你 2021-01-24 13:05

I\'ve written the following code in Python 3.x to validate the user\'s input:

while True:
    try:
        answer = int(input(\"Enter an integer: \"))
    except         


        
3条回答
  •  故里飘歌
    2021-01-24 13:11

    You can do this without relying on an exception using isdigit():

    answer = input("Enter an integer: ")
    while not answer.isdigit():
        print("That's not a whole number. Try again.")
        answer = input("Enter an integer: ")
    answer = int(answer)
    

    isdigit() tests to see if the input string is made up entirely of numbers that can be converted with int().

提交回复
热议问题