【问题标题】:How to write here? try: except for ZeroDivisionError: print "You cannot divide by zero!"这里怎么写?尝试:除了 ZeroDivisionError:打印“你不能被零除!”
【发布时间】:2021-05-28 23:52:57
【问题描述】:

求助,如何避免除法错误?

what = input ("+\n-\n/\n*\nЧто делаем?:")
a = float(input("\nВведите первое число:"))
b= float(input("Введите второе число:"))

if what == "+":
    c = a + b
    print("\nРезультат:" + str(c))

elif what == "/":
    c = a / b
    print("\nРезультат:" + str(c))


elif what == "*":
    c = a * b
    print("\nРезультат:" + str(c))

elif what == "-":
    c = a - b
    print("\nРезультат:" + str(c))

else:
    print ("\nНеизвестный символ.")
input()

在哪里插入? 尝试: 除了 ZeroDivisionError: print "Can't 除以零!"

【问题讨论】:

  • 哪里有分裂。比这更好的是,只需检查是否b != 0 而不是添加“try ... except ...”
  • 在 : elif what =='/': if(b!=0): c= a/b
  • 您使用 try 块来测试部分代码以应对最终异常,并使用 except 来管理可能发生的任何异常。跨度>

标签: python calculator


【解决方案1】:

你可以这样做

what = input ("+\n-\n/\n*\nЧто делаем?:")
a = float(input("\nВведите первое число:"))
b= float(input("Введите второе число:"))

if what == "+":
    c = a + b
    print("\nРезультат:" + str(c))

elif what == "/":
    try:
        c = a / b
        print("\nРезультат:" + str(c))
    except ZeroDivisionError:
        print("Can't divide by zero!")

elif what == "*":
    c = a * b
    print("\nРезультат:" + str(c))

elif what == "-":
    c = a - b
    print("\nРезультат:" + str(c))

else:
    print ("\nНеизвестный символ.")
input()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-11-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多