2017-08-09 34 views
1
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" 

此代碼不識別字母輸入。如何在給定一個數字位置的字母時停止程序崩潰?

+0

那是因爲你立即將其解析爲float。不要施加一個原始值,使其* *可以先被施放,可能試試:除了block –

+0

'employee = raw_input('僱員代碼號或0表示guest:')';'如果employee.isdigit() :employee = int(employee)else:else else ...' – Alexander

回答

0

使用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" 
0

您可以使用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) 
1

有2種方法。

  1. 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) 
  1. 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

+0

儘量避免選項1,除非有實際的理由。 – Jerrybibo

+0

返回此錯誤 如果(employee.isAlpha()): 文件「C:\ Users \ gavin.whitfort \ Desktop \ 2017 Work \ Software Devolpment \ SAT \ POS Solution.py」,行117,程序 AttributeError:'str'對象沒有屬性'isAlpha' >>> – GAVDADDY

+1

檢查alpha的正確方法是isalpha()。你應該對你的男人做一些研究。 –

0

如果你想讓它只能接受正整數您可以檢查使用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來檢查代碼,如果你是一個客人

相關問題