[英]ValueError when using Flag
這個問題的其他版本對我來說沒有意義。
ValueError:int() 的無效文字,基數為 10:'quit'
active = True
while active:
var = input()
if var == 'quit':
active = False
if int(var) < y
.
.
.
原代碼如下..
active = True
prompt = ("Please state your age.")
while active:
age = input(prompt)
if int(age) < 3:
print("Free")
elif int(age) >= 3 and int(age) <= 12:
print("$10")
elif int(age) > 12:
print("$15")
elif str(age) == 'quit':
active = False
您需要先檢查用戶輸入的類型。 您可以使用 try .. catch .. 語句。 如果用戶輸入不是整數或退出,則會顯示一條消息。
active = True
prompt = ("Please state your age.")
while active:
age = input(prompt)
if age == 'quit':
active = False
try:
val = int(age)
if val < 3:
print("Free")
elif val >= 3 and val <= 12:
print("$10")
else:
print("$15")
except ValueError:
print("Input string is not an Integer or 'quit'")
檢查if str(age) == 'quit':
必須發生在對int(age)
任何調用之前。 將該elif
移動到條件的頂部,並使if int(age) < 3
成為elif
。
在同一個字符串上調用int
是一種浪費,而在其中調用str
是不必要的。 您可以簡單地使用break
,而不是使用標志:
while True:
age = input(prompt)
if str(age) == 'quit':
break
age = int(age)
if age < 3:
print("Free")
elif 12 >= age >= 3:
print("$10")
elif age > 12:
print("$15")
您正在使用int(var)
將string
轉換為int
並且如果input()
(始終輸入字符串)不是數字類型,python 會給您一個type error
。
您可以使用isdigit()檢查input()
是否為數字類型,即:
arg = input("Type your age\n")
if arg.isdigit():
# input is numeric, do something with it
arg = int(arg)
else:
# input cannot be casted to an integer or decimal
exit(0)
str.isdigit()
如果字符串中的所有字符都是數字並且至少有一個字符,則返回true
否則返回false
。 數字包括十進制字符和需要特殊處理的數字,例如兼容性上標數字。 這涵蓋了不能用於形成以10為基數的數字的數字,例如 Kharosthi 數字。 正式地,數字是具有屬性值Numeric_Type=Digit
或Numeric_Type=Decimal
的字符。
筆記:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.