How to make a raw input a number?

This question already has an answer here:

  • How can I convert a string to an int in Python? 7 answers
  • How do I parse a string to a float or int in Python? 22 answers

  • times = int(raw_input('Enter a number: '))
    

    If someone enters in something other than an integer, it will throw an exception. If that's not what you want, you could catch the exception and handle it yourself, like this:

    try:
        times = int(raw_input('Enter a number: '))
    except ValueError:
        print "An integer is required."
    

    If you want to keep asking for input until someone enters a valid input, put the above in a while loop:

    while True:
        try:
            times = int(raw_input('Enter a number: '))
            break
        except ValueError:
            print "An integer is required."
    

    Wrap your input in int or float depending on the data type you are expecting.

    times = int(raw_input('Enter a number: '))
    print type(times)
    

    Outputs:

    Enter a number:  10
    <type 'int'>
    

    If a user inputs something other than a number, it will throw a ValueError (for example, inputing asdf results in:)

    ValueError: invalid literal for int() with base 10: 'asdf'
    

    您可以将输入转换为整数,如果不是,则捕获异常:

    try:
        times = int(raw_input('Enter a number: '))
        # do something with the int
    except ValueError:
        # not an int
        print 'Not an integer'
    
    链接地址: http://www.djcxy.com/p/48430.html

    上一篇: max()没有在列表中找到实际的最大值

    下一篇: 如何使原始输入数字?