employee = float(raw_input('Employee code number or 0 for guest:') or 0.0)
if employee == isalpha:
print "Nice try buddy"
print "Welcome BIG_OLD_BUDDY"
此代碼不識別字母輸入。如何在給定一個數字位置的字母時停止程序崩潰?
employee = float(raw_input('Employee code number or 0 for guest:') or 0.0)
if employee == isalpha:
print "Nice try buddy"
print "Welcome BIG_OLD_BUDDY"
此代碼不識別字母輸入。如何在給定一個數字位置的字母時停止程序崩潰?
使用try
try:
employee = float(raw_input('Employee code number or 0 for guest: ') or 0.0)
except ValueError:
print "Nice try buddy"
print "Welcome BIG_OLD_BUDDY"
您可以使用try/except
作爲對方的回答表明,如果你想使用str.isalpha()
你要調用它的字符串,而不是將其與字符串進行比較。例如:
employee = raw_input('Employee code number or 0 for guest:')
if employee.isalpha():
print "Nice try buddy"
print "Welcome BIG_OLD_BUDDY"
else:
employee = float(employee)
有2種方法。
- You can catch the the exceptions and pass.
try:
employee = float(raw_input('Employee code number or 0 for guest: ') or 0.0)
except KnownException:
# You can handle Known exception here.
pass
except Exception, e:
# notify user
print str(e)
- Check for the type of input and then do what you want to do.
employee = raw_input('Employee code number or 0 for guest:')
if(employee.isalpha()):
print "Nice try buddy"
print "Welcome BIG_OLD_BUDDY"
else:
print "Your employee no is:" + str(employee)
Do not use try and catch until and unless there are chances of unknown exceptions. To handle things with if and else are recommended.
Read more about : why not to use exceptions as regular flow of control
如果你想讓它只能接受正整數您可以檢查使用isdigit()
這基本上是isalpha()
。嘗試相反:
employee = raw_input('Employee code number or 0 for guest:')
if employee.isdigit()==False:
print "Nice try buddy"
print "Welcome BIG_OLD_BUDDY"
elif int(employee)==0:
print "You are a guest"
else:
print "Your employee no is:" ,employee
我也平添了幾分使用elif
來檢查代碼,如果你是一個客人
那是因爲你立即將其解析爲float。不要施加一個原始值,使其* *可以先被施放,可能試試:除了block –
'employee = raw_input('僱員代碼號或0表示guest:')';'如果employee.isdigit() :employee = int(employee)else:else else ...' – Alexander