计算器中的值错误

ValueError in calculator

我想知道,每当用户尝试输入 xy 中的字符串而不是整数时,是否可以显示消息“无效...”?

代码如下:

print("Enter a operator first ('+-*/') or 'q' to Exit! ")

while True:
    choice = input("Enter choice (one of these): '+', '-', '/', 'x': ")

    if choice in ('x+-/'):
        x = int(input("First number: "))
        y = int(input("Second number: "))

        if choice == "+":
            print(x, "+", y, "=", x + y)
        elif choice == "-":
            print(x, "-", y, "=", x - y)
        elif choice == "/":
            print(x, "/", y, "=", x / y)
        elif choice == "x":
            print(x, "x", y, "=", x * y)

    elif choice == 'q':
        break

    else:
        print("Invalid choice. Try again.")

我尝试了这些代码来解决我的问题但没有成功

if x != int:
    print("invalid...")
# And Also
if x == str:
    print ("invalid...")

也使用这些,并不能解决我的问题:

这是我得到的错误:

x = int(input("First number: "))
ValueError: invalid literal for int() with base 10: 'as'

我猜是因为我一开始就指出 x =input 必须是整数,但是如果我拿走这个 "int" 整个项目将无法运行,我会得到这个错误:

TypeError: can't multiply sequence by non-int of type 'str'

是的,这是可能的。使用 try/except 块如下:

try:
    x = int(input("First number:"))
    y = int(input("Second number: "))
except ValueError:
    print('Invalid...')


你可以这样做:

while True:
    choice = input("Enter choice (one of these): '+', '-', '/', 'x': ")

    if choice in ('x+-/'):
        x = input("First number: ")
        y = input("Second number: ")

        if x.isalpha() or y.isalpha():
            print("invalid...")
        else:
            x=int(x)
            y=int(y)

            if choice == "+":
              print(x, "+", y, "=", x + y)
            elif choice == "-":
              print(x, "-", y, "=", x - y)
            elif choice == "/":
              print(x, "/", y, "=", x / y)
            elif choice == "x":
              print(x, "x", y, "=", x * y)

            elif choice == 'q':
              break

    else:
        print("Invalid choice. Try again.")