python 处理来自用户的无效输入
python handling invalid inputs from a user
我被这个作业卡住了:
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)
我试过尝试了 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")
那是因为你可能没有考虑到 y = 0 时得到的 ZeroDivisionError
!
怎么样
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
此函数正好计算出 3 个正确的除法 x/y!
如果您需要有关 continue
运算符的良好参考,请查看 here
我被这个作业卡住了:
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)
我试过尝试了 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")
那是因为你可能没有考虑到 y = 0 时得到的 ZeroDivisionError
!
怎么样
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
此函数正好计算出 3 个正确的除法 x/y!
如果您需要有关 continue
运算符的良好参考,请查看 here