【问题标题】:I want to make python identify if `num1` and `num2` were numbers or not in this calculator so that python can notify you're not typing in valid things [duplicate]我想让python在这个计算器中识别“num1”和“num2”是否是数字,以便python可以通知你没有输入有效的东西[重复]
【发布时间】:2019-06-17 16:56:14
【问题描述】:

我想让python识别num1num2在这个计算器中是否是数字,以便python可以通知你没有输入有效的东西。也许使用 if 语句?

num1 = float(input("Enter a number: "))
num2 = float(input("Enter a number: "))
op = input("What operator would you use?")
if op == "+":
    print(num1 + num2)
elif op == "-":
    print(num1 - num2)
elif op == "*":
    print(num1 * num2)
elif op == "/":
    print(num1 / num2)
else:
    print("Invalid operator")

【问题讨论】:

    标签: python


    【解决方案1】:

    您可以将其包装在 try-except 块中:

    try:
        num1 = float(input("Enter a number: "))
        num2 = float(input("Enter a number: "))
    except ValueError:
        print("Invalid number")
    

    如果您想继续提示用户:

    while True:
        try:
            num1 = float(input("Enter a number: "))
            break
        except:
            print("Invalid number")
    

    num2 做同样的事情。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-08-19
      • 1970-01-01
      • 2021-08-26
      • 1970-01-01
      • 2011-07-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多