python - 如何检查 Python 中的整数输入?

标签 python input

我用过:

day = int(input('Please input the day you were born: e.g 8th=8 21st = 21 : '))
month = int(input('Please input the month you were born: e.g may = 5 december = 12 : '))
year = int(input('Please input the year you were born: e.g 2001 / 1961 : '))

if day == int and month == int and year == int:

但即使它是一个整数,它也总是说它是错误的。

最佳答案

def get_int(p,error_msg="Thats Not An Int!"):
    while True:
         try:
            return int(raw_input(p))
         except (ValueError,TypeError):
            print "ERROR: %s"%error_msg

day = get_int('Please input the day you were born: e.g 8th=8 21st = 21 : ')
#day is guaranteed to be an int

我喜欢把它进一步抽象化

 def force_type(type_class,prompt,error_msg):
     while True:
         try:
            return type_class(prompt)
         except (ValueError,TypeError):
            print error_msg

然后就变成了

 def get_int(p,err_msg):
     return force_type(int,p,err_msg)
 def get_float(p,err_msg):
     return force_type(float,p,err_msg)
 ...

所有这些都说如果你想进行类型检查你应该~~使用type(var)你应该使用isinstance(var,int)

关于python - 如何检查 Python 中的整数输入?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33680570/

相关文章:

python - 使用 API 访问 sqlalchemy 中的关系表数据

python - 如何设置守护进程在其死亡时杀死其进程组中的其他进程

c++ - 控制台输入-按回车后清除

iphone - 可编辑的表格 View 单元格

android - 更改 EditPreference 的输入类型

python-3.x - 如何解决 python 中 input() 的问题?

python - 在 __init__ 中解压 **kwargs

python - Pandas groupby 列值的变化

python - 如何创建一个可以使用或不使用参数的装饰器?

Android 和声音处理?