首页 > 解决方案 > 当用户假设按数字而不是字母时如何使我的程序运行

问题描述

我正在制作计算器,例如,当用户不小心输入字母而不是数字时,程序就会崩溃。如何通过说“按下错误的键”来使其运行,并且只要有人键入字母,它就会继续打印该消息。直到用户输入一个数字,它才会继续。例如,在我的代码中,我想让 num1 和 num2 打印出“错误的按键错误”,而不是人们输入字母而不是数字。

编辑:我还希望结局在按下“y”和“n”以外的任何键时打印出错误消息

这是我的代码

def calculator():

    print("")  # leaves a line space
    num1 = float((input("Enter first number ")))
    operator = input("Enter an operator ")
    num2 = float(input("Enter second number "))

    if num1 == str:
        print("Error: wrong key pressed")

    if num2 == str:
        print("Error: wrong key pressed")


    if operator == "+":
        print(num1 + num2)
    elif operator == "-":
        print(num1 - num2)
    elif operator == "*":
        print(num1 * num2)
    elif operator == "/":
        if num2 == 0:
            print("Error: You cannot divide a number by 0")
        else:
            print(num1 / num2)
    else:
        print("Error wrong key pressed")

    restart = input("Press \"y\" to continue. If you wish to leave press \"n\" ")

    if restart.lower() == "y":
        calculator()
    elif restart.lower() == "n":
        print("Bye!")
        exit()


calculator()

标签: python

解决方案


只需像这样在您的输入语句周围添加一个 try catch。

def calculator():

    print("")  # leaves a line space
    num1 = 0
    num2 = 0
    try:
        num1 = float((input("Enter first number ")))
        operator = input("Enter an operator ")
        num2 = float(input("Enter second number "))
    except Exception as e:
        print("Error: wrong key pressed")
        calculator()

    if num1 == str:
        print("Error: wrong key pressed")

    if num2 == str:
        print("Error: wrong key pressed")


    if operator == "+":
        print(num1 + num2)
    elif operator == "-":
        print(num1 - num2)
    elif operator == "*":
        print(num1 * num2)
    elif operator == "/":
        if num2 == 0:
            print("Error: You cannot divide a number by 0")
        else:
            print(num1 / num2)
    else:
        print("Error wrong key pressed")

    restart = input("Press \"y\" to continue. If you wish to leave press \"n\" ")

    if restart.lower() == "y":
        calculator()
    elif restart.lower() == "n":
        print("Bye!")
        exit()

calculator() 

在里面try我们编写语句,如果发生异常,它将在catch语句中捕获。在您的情况下,我们将再次调用计算器程序。


推荐阅读