【问题标题】:I wrote a calculator together with a error handling but I do not understand why it doesnt work?我写了一个计算器和一个错误处理,但我不明白为什么它不起作用?
【发布时间】:2022-11-14 06:18:17
【问题描述】:
def arithmetic_sequence():
    a = float(input('Type the first term'))
    d = float(input('Type the difference'))
    n = float(input("Type the number of values"))
    if a == ValueError:
        print("Write a value")
    elif d == ValueError:
        print("Write a value")
    elif n == ValueError:
        print("Write a value")
    else:
        sum = float(n * (a + (a + d * (n - 1))) / 2)
        return sum
print(arithmetic_sequence())

我的目标是当一个人在程序中写入一个非数字让它说写一个值但它只显示ValueError,为什么?我专门在程序中写了“键入一个值”。

【问题讨论】:

标签: python python-3.x


【解决方案1】:

当 Python 无法将用户的字符串转换为 float 时,它会增加一个ValueError 不返回一个。您需要像这样捕获错误:

try:
    a = float(input("Type the first term"))
except ValueError:
    print("Write a value")

【讨论】:

    【解决方案2】:
    def arithmetic_sequence():
        try:
            a = float(input('Type the first term:'))
            d = float(input('Type the difference:'))
            n = float(input("Type the number of values:"))
            return float(n * (a + (a + d * (n - 1))) / 2)
        except ValueError:
            print("Write a value")
    
    
    print(arithmetic_sequence())
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-01-22
      • 1970-01-01
      • 2022-01-06
      • 2021-07-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多