我试图检查用户输入的字符串的长度以及它是否< 5然而无论多长,它仍然通过我的尝试除了声明
print“”“ 请输入公司的股票代码 你希望看到它的最后收盘价。“”“
while True:
symbol = raw_input("Enter Stock Symbol: ")
try:
len(symbol) < 5
break
except ValueError:
print 'Greater than 4 characters, Try again'
print 'Great your stock symbol is less than 5'
答案 0 :(得分:6)
你不需要尝试/除了:
while True:
symbol = raw_input("Enter Stock Symbol: ")
if len(symbol) > 4:
print 'Greater than 4 characters, Try again'
else:
print 'Great your stock symbol {} is less than 5'.format(symbol)
break
In [3]: paste
while True:
symbol = raw_input("Enter Stock Symbol: ")
if len(symbol) > 4:
print 'Greater than 4 characters, Try again'
else:
print 'Great your stock symbol {} is less than 5'.format(symbol)
break
## -- End pasted text --
Enter Stock Symbol: FOOBAR
Greater than 4 characters, Try again
Enter Stock Symbol: YHOO
Great your stock symbol YHOO is less than 5
在您的代码中:
try:
len(symbol) < 5 # always checks len
break # always breaks
except ValueError:
如果您希望将输入转换为try/except
来捕获ValueError,那么您将使用int
,但它不适用于您的情况。
答案 1 :(得分:0)
您必须首先在 if 语句的 try 部分中调用(TypeError 或 ValueError 或 ..Error),并在 except 部分决定如何处理此错误.更多信息:here
while True:
name = input (': ')
try:
if (len (name) >= 4):
raise ValueError()
break
except ValueError:
print ('Account Created')
else:
print ('Invalid Input')