2017-08-09 8 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

しているかどうかをチェックするためにelifを使用してコードのビットを追加しました。 –

+0

'employee = raw_input( '従業員コード番号または0はゲスト:')'; 'もしemployee.isdigit()ならば、あなたは生の値をキャストしないでください。 :employee = int(従業員)else:他の何か... ' – Alexander

答えて

0

は試す

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

このエラーが返されます ファイル のファイル "C:¥Users¥gavin.whitfort¥Desktop¥2017 Work¥Software Devolpment¥SAT¥POS Solution.py" 117行目の場合、(employee.isAlpha()): AttributeError: 'str'オブジェクトに 'isAlpha'属性がありません >>> – GAVDADDY

+1

アルファをチェックする正しい方法はisalpha()です。あなたはあなたの人を研究しなければなりません。 –

0

あなたはそれが唯一あなたが基本的にisalpha() .Tryの反対であるisdigit()を使用して確認することができます正の整数を受け入れる場合:

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 

私はまた、あなたがすぐにfloatとしてそれを解析しているためだゲスト

関連する問題