Python - User input data type

前端 未结 3 945
我在风中等你
我在风中等你 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().

    0 讨论(0)
  • 2021-01-24 13:14

    String, everything that you input() will be a string. And all of them will raise value error except for C-c if int() raises it.

    0 讨论(0)
  • 2021-01-24 13:19

    Assuming you're using python 3.X, everything the user inputs will be a string. Even numbery looking things like "23" or "0". int(thing) doesn't validate that thing is of the integer type. It attempts to convert thing from whatever type it is now, into the integer type, raising a ValueError if it's impossible.

    Demonstration:

    >>> while True:
    ...     x = input("Enter something: ")
    ...     print("You entered {}".format(x))
    ...     print("That object's type is: {}".format(type(x)))
    ...
    Enter something: hi
    You entered hi
    That object's type is: <class 'str'>
    Enter something: hi46
    You entered hi46
    That object's type is: <class 'str'>
    Enter something: 
    You entered
    That object's type is: <class 'str'>
    Enter something: ]%$
    You entered ]%$
    That object's type is: <class 'str'>
    Enter something: 23
    You entered 23
    That object's type is: <class 'str'>
    Enter something: 42
    You entered 42
    That object's type is: <class 'str'>
    Enter something: 0
    You entered 0
    That object's type is: <class 'str'>
    
    0 讨论(0)
提交回复
热议问题