[英]Testing if user input is an int or a str, then failing if input is a str. I keep getting strs I enter as undefined
我正在嘗試測試我的用戶輸入是字符串還是整數。
feet = input ("Enter your feet.")
inches = input ("Enter your inches.")
if type(eval(feet)) and type(eval(inches)) == int:
print ("both are numbers!")
else:
print ("That's not a Number!")
這是我的代碼,如果我輸入數字作為英尺和英寸的值,它將起作用。 但是,如果foot = a,則會收到錯誤消息,指出a未定義。
我究竟做錯了什么?
您做錯的是使用eval
。 那絕不是做任何事情的好方法。
相反,嘗試轉換為int並捕獲異常:
try:
feet = int(feet)
inches = int(inches)
except ValueError:
print("not numbers!")
else:
print("numbers!")
不要使用eval
來測試用戶輸入是否為整數。 因為解釋器試圖找到一個叫做a
的變量,但沒有定義一個變量,所以會出現錯誤。 相反,您可以檢查字符串是否僅包含數字。
def is_integer(s):
for c in s:
if not c.isdigit():
return False
return True
feet = input ("Enter your feet.")
inches = input ("Enter your inches.")
if is_integer(feet) and is_integer(inches):
print ("both are numbers!")
else:
print ("That's not a Number!")
假設負數無效。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.