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:
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
実用的な理由がない限り、オプション1を避けてください。 – Jerrybibo
このエラーが返されます ファイル のファイル "C:¥Users¥gavin.whitfort¥Desktop¥2017 Work¥Software Devolpment¥SAT¥POS Solution.py" 117行目の場合、(employee.isAlpha()): AttributeError: 'str'オブジェクトに 'isAlpha'属性がありません >>> – GAVDADDY
アルファをチェックする正しい方法はisalpha()です。あなたはあなたの人を研究しなければなりません。 –
あなたはそれが唯一あなたが基本的に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としてそれを解析しているためだゲスト
しているかどうかをチェックするために
elif
を使用してコードのビットを追加しました。 –'employee = raw_input( '従業員コード番号または0はゲスト:')'; 'もしemployee.isdigit()ならば、あなたは生の値をキャストしないでください。 :employee = int(従業員)else:他の何か... ' – Alexander