[英]python handling invalid inputs from a user
I am stuck with this homework:我被这个作业困住了:
rewrite the following program so that it can handle any invalid inputs from user.
重写以下程序,以便它可以处理来自用户的任何无效输入。
def example():
for i in range(3)
x=eval(input('Enter a number: '))
y=eval(input('enter another one: '))
print(x/y)
l tried tried the try... except ValueError, but the program is still failing to run.我试了试try...除了ValueError,但程序仍然无法运行。
def example():
for i in range(3)
try:
x=eval(input('Enter a number: '))
except ValueError:
print("Sorry, value error")
try:
y=eval(input('enter another one: '))
except ValueError:
print("Sorry, value error")`enter code here`
try:
print(x/y)
except ValueError:
print("Sorry, cant divide zero")
That's because you probably didn't consider the ZeroDivisionError
that you get when y = 0!那是因为您可能没有考虑 y = 0 时得到的
ZeroDivisionError
! What about关于什么
def example():
for i in range(3):
correct_inputs = False
while not correct_inputs:
try:
x=eval(input('Enter a number: '))
y=eval(input('enter another one: '))
print(x/y)
correct_inputs = True
except:
print("bad input received")
continue
This function computes exactly 3 correct divisions x/y!这个 function 精确计算了 3 个正确的除法 x/y! If you need a good reference on
continue
operator, please have a look here如果您需要有关
continue
运算符的良好参考,请查看此处
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.