首页 > 解决方案 > ValueError 和 ZeroDivisionError

问题描述

我正在尝试执行计算 ((x/y) + z) 并解释 2 个错误:ValueErrorZeroDivisionError.

但是,我很难理解如何将这 2 个错误编码到我的程序中。我想我已经ValueError想通了,但没有ZeroDivisionError。这是我到目前为止所拥有的。对不起,它很乱rn....

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, y, z, calculate(x, y, z)))

标签: pythonvalueerror

解决方案


我不明白你为什么需要 try/except/except 块。您已经y=0在您的calculate方法中进行了检查,并且您已经知道您有有效的输入,否则splitand 强制转换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, y, z, calculate(x, y, z)))

推荐阅读