簡體   English   中英

如何檢查Python中的整數輸入?

[英]How do I check an input for an integer in Python?

我用了:

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)你應該〜 〜使用type(var)你應該使用isinstance(var,int)

要檢查類型,您可以:

type(aVar) is aType

無論如何,正如凱文在評論中所說,你已經將輸入包裝到int中,所以它實際上是一個int或你的程序崩潰了

嘗試

if type(day) == int and type(month) == int and type(year) == int

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM