避免 while 循环外的 ValueError?
Avoid ValueError outside a while loop?
在第二行中,我试图让它在输入字符串时不会崩溃,但找不到使用异常或类似内容的方法。在 while 循环中它正常工作,因为异常处理这种情况。
number = 0 #this to be removed
number = (float(input('pick a number'))) #I want to make this not crash if a string is entered.
while number not in [100, 200, 3232]:
try:
print('wrong number ')
number = (float(input('pick a number;'))) #Here it does not crash if a string is entered which is fine
except ValueError:
print("retry")
while
后跟可变条件通常以 bugs/repeating 代码 => 可维护性差结束。
使用 while True
条件来避免重复您的代码,然后在有效时中断循环。
while True:
try:
number = float(input('pick a number;'))
if number in [100, 200, 3232]:
break
print("wrong number")
except ValueError:
print("illegal number, retry")
注意:在一般情况下要小心浮点数相等(另请参阅 strange output in comparison of float with float literal, Is floating point math broken?)
也许创建一个函数来接受输入:
def get_input():
while True:
a = input("Pick a number: ")
try:
return float(a)
except:
pass
在第二行中,我试图让它在输入字符串时不会崩溃,但找不到使用异常或类似内容的方法。在 while 循环中它正常工作,因为异常处理这种情况。
number = 0 #this to be removed
number = (float(input('pick a number'))) #I want to make this not crash if a string is entered.
while number not in [100, 200, 3232]:
try:
print('wrong number ')
number = (float(input('pick a number;'))) #Here it does not crash if a string is entered which is fine
except ValueError:
print("retry")
while
后跟可变条件通常以 bugs/repeating 代码 => 可维护性差结束。
使用 while True
条件来避免重复您的代码,然后在有效时中断循环。
while True:
try:
number = float(input('pick a number;'))
if number in [100, 200, 3232]:
break
print("wrong number")
except ValueError:
print("illegal number, retry")
注意:在一般情况下要小心浮点数相等(另请参阅 strange output in comparison of float with float literal, Is floating point math broken?)
也许创建一个函数来接受输入:
def get_input():
while True:
a = input("Pick a number: ")
try:
return float(a)
except:
pass