为了账号安全,请及时绑定邮箱和手机立即绑定

值错误和零除错误

值错误和零除错误

慕田峪9158850 2023-10-26 10:19:08
我正在尝试执行计算 ((x/y) + z) 并解释 2 个错误:ValueError和ZeroDivisionError.但是,我很难理解如何将这两个错误编码到我的程序中。我想我已经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 ctry:    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)))
查看完整描述

4 回答

?
POPMUISE

TA贡献1765条经验 获得超5个赞

恭喜你学习了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, y, 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, y, z, calculate(x, y, 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, y, 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, y, 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, y, z)


except ValueError:

    print(user_input," is not valid input.")


查看完整回答
反对 回复 2023-10-26
?
HUH函数

TA贡献1836条经验 获得超4个赞

我只是调整了您的代码以满足您的期望,并且易于理解。


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, y, z, c))


查看完整回答
反对 回复 2023-10-26
?
小唯快跑啊

TA贡献1863条经验 获得超2个赞

我根本不明白为什么你需要 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, y, z, calculate(x, y, z)))


查看完整回答
反对 回复 2023-10-26
?
蓝山帝景

TA贡献1843条经验 获得超7个赞

您引发了一个异常来查看 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, y, 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, y, z, calculate(x, y, z)))


查看完整回答
反对 回复 2023-10-26
  • 4 回答
  • 0 关注
  • 135 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信