[英]How do I stop the program from crashing when given a letter in the place of a number?
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"
This code does not recognize alphabetical input. 该代码无法识别字母输入。
There are 2 ways. 有两种方法。
- 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.
除非有可能出现未知异常,否则不要使用try and catch。 To handle things with if and else are recommended.
建议使用if和else处理。
Read more about : why not to use exceptions as regular flow of control 阅读有关以下内容的更多信息:为什么不将异常用作常规控制流
Use a 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"
You can use try/except
as the other answer suggested, and if you want to use str.isalpha()
you have to call it on the string, not compare it with the string. 您可以使用
try/except
作为其他建议的答案,如果要使用str.isalpha()
,则必须在字符串上调用它,而不是将其与字符串进行比较。 For example: 例如:
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)
If you want it to only accept positive integers you can check using isdigit()
which is basically the opposite of isalpha()
.Try: 如果您希望它只接受正整数 ,则可以使用
isdigit()
进行检查,而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
I also added a bit of code using elif
to check if you're a guest 我还使用
elif
添加了一些代码来检查您是否是访客
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.