python - 如何在我的第一个 python 计算器中修复这个 while 循环?

标签 python error-handling while-loop calculator

首先,我是Python新手。我正在尝试我的第一个程序,但目前陷入困境。我陷入了第二个 while 循环,程序要求用户输入正确的运算符。我希望程序不断询问正确的运算符,直到用户输入一个,然后我希望执行 num2 变量。问题是 vatiables op 和 num2 将被执行,然后我会看到错误消息,之后它将循环回 op。我该如何编写它,这样我就不必编写第三个 while 循环来处理 num2 的错误,因为我会收到一条错误,指出 num2 被调用但未在 op 循环中定义?请帮忙。代码如下:

print("                      Welcome to Calculator!")

print("\n********************************************************************\n")

...

user_instructions =('''
Instructions:

Type in a number, then press Enter.
Type in an available Operator, followed by Enter.
Type in another number, then press Enter.''')

def instructions():
    print(user_instructions)

instructions()

operator_list =('''
Below is the list of available operators:

+ for Addition
- for Subtraction
/ for Division
* for Multiplication
^ for exponents
r for root
% for modulus''')


def calculate():
    print(operator_list)
    print("\n********************************************************************\n")


    while True:
        try:
           num1 = float(input("Enter a number: "))
           break
        except ValueError:
            print("Invalid input. Please try again...")
            print("\n********************************************************************\n")
      
    
    while True:
        try:
           op = input("Enter an operator: ")
           num2 = float(input("Enter another number: "))
           break
        except ValueError:
            print("Invalid input. Please try again...")

            

    if op == "+":
        print('{} + {} = '.format(num1, num2))
        print("\n")
        print(num1 + num2)
    elif op == "-":
        print('{} - {} = '.format(num1, num2))
        print("\n")
        print(num1 - num2)
    elif op == "/":
        if num2 == 0:
            print('Math error! Cannot divide by zero!')
        else:
            print('{} / {} = '.format(num1, num2))
            print("\n")
            print(num1 / num2)
    elif op == "*":
        print('{} * {} = '.format(num1, num2))
        print("\n")
        print(num1 * num2)
    elif op == "^":
        print('{} ^ {} = '.format(num1, num2))
        print("\n")
        print(num1 ** num2)
    elif op == "r":
        print('{} root {} = '.format(num1, num2))
        print("\n")
        print(num2 ** (1/num1))
    elif op == "%":
        print('{} % {} = '.format(num1, num2))
        print("\n")
        print(num1 % num2)
    else:
        print("Invalid Input. Please try again")
        print("\n********************************************************************\n")     

calculate() 

print("\n********************************************************************\n")

def again():
    calc_again = input('''
    Would you like to calculate again?
    Please type Y for YES or N for No.
    ''')

    print("\n********************************************************************\n")
    
    if calc_again.upper() == 'Y':
        calculate()
        print("\n********************************************************************\n")
        again()

    elif calc_again.upper()  == 'N':
        print("Thank you for using Calculator, Goodbye...") 
        import sys
        sys.exit()
        
    else:
        print("Invalid Input. Please try again...")

        print("\n********************************************************************\n")

        again()
        print("\n********************************************************************\n")
        calculate()


again()

最佳答案

您可以让函数calculate()调用自身,具体方法如下:

print("                      Welcome to Calculator!")

print("\n********************************************************************\n")

...

user_instructions =('''
Instructions:

Type in a number, then press Enter.
Type in an available Operator, followed by Enter.
Type in another number, then press Enter.''')

def instructions():
    print(user_instructions)

instructions()

operator_list =('''
Below is the list of available operators:

+ for Addition
- for Subtraction
/ for Division
* for Multiplication
^ for exponents
r for root
% for modulus''')


def calculate():
    print(operator_list)
    print("\n********************************************************************\n")


    while True:
        try:
           num1 = float(input("Enter a number: "))
           break
        except ValueError:
            print("Invalid input. Please try again...")
            print("\n********************************************************************\n")
      
    
    while True:
        try:
           op = input("Enter an operator: ")
           num2 = float(input("Enter another number: "))
           break
        except ValueError:
            print("Invalid input. Please try again...")

            

    if op == "+":
        print('{} + {} = '.format(num1, num2))
        print("\n")
        print(num1 + num2)
    elif op == "-":
        print('{} - {} = '.format(num1, num2))
        print("\n")
        print(num1 - num2)
    elif op == "/":
        if num2 == 0:
            print('Math error! Cannot divide by zero!')
        else:
            print('{} / {} = '.format(num1, num2))
            print("\n")
            print(num1 / num2)
    elif op == "*":
        print('{} * {} = '.format(num1, num2))
        print("\n")
        print(num1 * num2)
    elif op == "^":
        print('{} ^ {} = '.format(num1, num2))
        print("\n")
        print(num1 ** num2)
    elif op == "r":
        print('{} root {} = '.format(num1, num2))
        print("\n")
        print(num2 ** (1/num1))
    elif op == "%":
        print('{} % {} = '.format(num1, num2))
        print("\n")
        print(num1 % num2)
    else:
        print("Invalid Input. Please try again")
        print("\n********************************************************************\n")


    while True:
        calc_again = input('''
        Would you like to calculate again?
        Please type Y for YES or N for No.
        ''')

        print("\n********************************************************************\n")
        
        if calc_again.upper() == 'Y':
            calculate()
            break

        elif calc_again.upper()  == 'N':
            print("Thank you for using Calculator, Goodbye...") 
            import sys
            sys.exit()
            
        else:
            print("Invalid Input. Please try again...")
            print("\n********************************************************************\n")



calculate()

顺便说一句,代码非常详尽,干得好!

关于python - 如何在我的第一个 python 计算器中修复这个 while 循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63183246/

相关文章:

java - 在 Android 应用程序中为 Toast 编写 JUnit 测试

r - 如何将警告()输出到字符串

error-handling - 如何处理 Wicket 自定义模型中抛出的异常?

c - 同一行 C 中的 `if` 和 `while` 语句,没有明显的分支或循环

Python Firebase Admin SDK 似乎成功,但我从未收到通知

python - 如果值落在某个范围内,则根据另一列的条件创建新列

python - 了解 Django 查询集字段查找

javascript - 从内部函数体内跳出 while 循环

python - 寻求在 Python 中设计 While 循环的帮助

python - 将 Z3Py 与 Python 3.3 结合使用