Python - User input data type

前端 未结 3 978
我在风中等你
我在风中等你 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: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: 
    Enter something: hi46
    You entered hi46
    That object's type is: 
    Enter something: 
    You entered
    That object's type is: 
    Enter something: ]%$
    You entered ]%$
    That object's type is: 
    Enter something: 23
    You entered 23
    That object's type is: 
    Enter something: 42
    You entered 42
    That object's type is: 
    Enter something: 0
    You entered 0
    That object's type is: 
    

提交回复
热议问题