如何使原始输入数字?

这个问题在这里已经有了答案:

  • 如何将字符串转换为Python中的int? 7个答案
  • 如何在Python中将字符串解析为float或int? 22个答案

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

    如果某人输入的不是整数,它会抛出异常。 如果这不是你想要的,你可以捕获异常并自己处理,如下所示:

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

    如果你想继续询问输入,直到有人输入一个有效的输入,把上面的代码放在while循环中:

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

    将输入用intfloat具体取决于您期望的数据类型。

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

    输出:

    Enter a number:  10
    <type 'int'>
    

    如果用户输入的不是数字,它会抛出一个ValueError (例如,输入asdf结果:)

    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/48429.html

    上一篇: How to make a raw input a number?

    下一篇: How to force integer input in Python 3.x?