如何解决ValueError和ZeroDivisionError
我正在尝试执行((x / y)+ z)的计算,并解决了2个错误:ValueError
和ZeroDivisionError.
但是,我很难理解如何将这两个错误编码到我的程序中。我想我已经ValueError
知道了,但是ZeroDivisionError
没有。到目前为止,这就是我所拥有的。抱歉,它太乱了。...
user_input = (input("Enter three numbers separated by a space: ")).split()
x = int(user_input[0])
y = int(user_input[1])
z = int(user_input[2])
def calculate(x,y,z):
'''calculate (x/y)+z'''
c = ((x/y) + z) if y != 0 else print("Second input value cannot be 0")
return c
try:
input_values_str = str(user_input)
c = ((x/y) + z)
for val in input_values_str:
if len(user_input) == 3:
print("Correct number of values.")
else:
print("Incorrect number of values entered.")
except ValueError:
print(user_input," is not valid input.")
except ZeroDivisionError:
y = 0
print("Second value cannot be 0")
print("Formula: ({}/{}) + {} = {}".format(x,z,calculate(x,z)))
解决方法
我根本不明白为什么您需要try / except / except块。您已经在y=0
方法中检查calculate
,并且已经知道输入有效,或者split
并且强制转换int()
失败。那里的for
循环一遍又一遍地打印相同的输出字符串。如果将所有内容都排除掉,您的代码似乎可以正常工作
try:
file_name = open('/tmp/data.txt','r')
except FileNotFoundError:
print("File could not be found. Please check spelling of file name!")
sys.exit()
#Read lines in file
Lines = file_name.read().splitlines()
user_input = (input("Enter three numbers separated by a space: ")).split()
x = int(user_input[0])
y = int(user_input[1])
z = int(user_input[2])
def calculate(x,y,z):
'''calculate (x/y)+z'''
c = ((x / y) + z) if y != 0 else print("Second input value cannot be 0")
return c
print("Formula: ({}/{}) + {} = {}".format(x,z,calculate(x,z)))
,
您提出了一个异常以查看y == 0,但第一个值(x)也不能为0。并且您需要将2个if语句放在c = ...
之前尝试一下:
user_input = (input("Enter three numbers separated by a space: ")).split()
x = int(user_input[0])
y = int(user_input[1])
z = int(user_input[2])
def calculate(x,z):
'''calculate (x/y)+z'''
if y == 0 or x == y:
print("Invalid Input")
else:
c = ((x/y) + z)
return c
try:
input_values_str = str(user_input)
c = ((x/y) + z)
for val in input_values_str:
if len(user_input) == 3:
print("Correct number of values.")
else:
print("Incorrect number of values entered.")
except ValueError:
print(user_input," is not valid input.")
except ZeroDivisionError:
y = 0
x = 0
print("Second value cannot be 0. First Value cannot be 0")
print("Formula: ({}/{}) + {} = {}".format(x,z)))
,
我只是对您的代码进行了调整以满足您的期望,并且易于理解。
user_input = (input("Enter three numbers separated by a space: ")).split()
x = int(user_input[0])
y = int(user_input[1])
z = int(user_input[2])
try:
c = ((x/y) + z) if y != 0 else print("Second input value cannot be 0")
except ValueError:
print(user_input," is not valid input.")
print("Formula: ({}/{}) + {} = {}".format(x,c))
,
恭喜您学习Python!我认为您的代码有些混乱。我将用一些评论发布您的版本,然后发布一个清理过的版本,我认为它可以更好地实现您的目标。希望这是指导性的。这样做有更优雅的方法,但是我正尽力保留您的结构。
您的代码:
user_input = (input("Enter three numbers separated by a space: ")).split()
x = int(user_input[0])
y = int(user_input[1])
z = int(user_input[2])
def calculate(x,z):
c = ((x/y) + z) if y != 0 else print("Second input value cannot be 0") #Why do you need a ZeroDivisonError check below when you check for Zero here?
return c
try:
input_values_str = str(user_input) # why are you taking an input here? Did you take the input above? And why convert it back into a string?
c = ((x/y) + z)
for val in input_values_str: # Why are you iterating through string? You're basically checking 3 times if the length of your string is 3 characters
if len(user_input) == 3:
print("Correct number of values.")
else:
print("Incorrect number of values entered.")
except ValueError:
print(user_input," is not valid input.")
except ZeroDivisionError:
y = 0 # why set y back to zero in the event oa ZeroDivisonError? Won't that just create a ZeroDivison Error? Might make more sense to get a new input from the user
print("Second value cannot be 0")
print("Formula: ({}/{}) + {} = {}".format(x,z))) # if the objective is to only print something,why not do it in the calculate function? Then we can contain your ZeroDivisionError in their and request a new y
我的代码:
def calculate(x,z):
try:
solution = (x/y) + z
print(f"Formula: ({x}/{y}) + {z} = {solution}")
except ZeroDivisionError:
y = int(input("2nd value cannot be a Zero. Please input a new y value: "))
calculate(x,z)
try:
user_input = (input("Enter three numbers separated by a space: ")).split()
while len(user_input) != 3:
print("Incorrect number of values entered.")
user_input = (input("Enter three numbers separated by a space: ")).split()
x = int(user_input[0])
y = int(user_input[1])
z = int(user_input[2])
calculate(x,z)
except ValueError:
print(user_input," is not valid input.")
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。