[英]Making a variable integer input only == an integer in Python
我試圖使我的變量整數輸入僅為==整數,如果不是,我想打印並顯示錯誤消息。 我已將其放在if語句中。 當我輸入字符串而不是錯誤消息時,總是出現錯誤。
age = int(input("Enter age:"))
if age != int:
print("Not a number")
您必須使用raw_input
代替輸入
如果您要重復此操作直到您擁有正確的值,就可以這樣做
while True:
try:
age = int(raw_input("Enter age:"))
except ValueError:
print("Not a number")
if age == desired_age: # note I changed the name of your variable to desired_age instead of int
break
我不建議您使用像int這樣的變量名。
從討論中,我發布了上面的鏈接:
age = input("Enter age:") # raw_input("Enter age:") in python 2
try:
age = int(age)
except ValueError:
print('not a number!')
這個想法是嘗試將age
轉換為整數。
您的age != int
嘗試age != int
總是會失敗; age
是一個字符串(如果成功轉換,則為int
),而int
是一個類。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.