简体   繁体   English

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

[英]How can I fix this while loop in my first python calculator?

First off, I am new to python.首先,我是 python 的新手。 I am attempting my first program, and I am currently stuck.我正在尝试我的第一个程序,但我目前陷入困境。 I am stuck at the second while loop where the program asks the user to input a correct operator.我被困在第二个while循环中,程序要求用户输入正确的运算符。 I want the program to keep asking for a correct operator until the user enters one, and then I want num2 variable to be executed.我希望程序一直要求正确的运算符,直到用户输入一个,然后我希望执行 num2 变量。 The problem is that vatiables op and num2 will be executed, and then I'll see the error message, after which, it'll loop back to op.问题是变量 op 和 num2 将被执行,然后我会看到错误消息,然后它会循环回到 op。 How can I write it so that I won't have to write a third while loop for error handling of num2, because I will get an error stating that num2 is called but not defined in the loop for op?我该如何编写它,这样我就不必为 num2 的错误处理编写第三个 while 循环,因为我会收到一个错误,指出调用了 num2 但未在 op 的循环中定义? Please help.请帮忙。 Code is below:代码如下:

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()

You most likely want to check your user's input within the same while loop that you ask them to enter an operator using an if statement.您很可能希望在要求他们使用 if 语句输入运算符的同一个 while 循环中检查用户的输入。

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

Instead of allowing a break immediately after you receive input, you'll want to add a conditional statement after the operator input to verify they entered a valid value.与其在收到输入后立即允许中断,不如在操作员输入后添加条件语句以验证他们输入的值是否有效。

if(op != "+" or op != "-"): #Etc...
      continue

continue Skips the remainder of the loop, and moves on to the next iteration, which will prompt the user again for an operator. continue 跳过循环的其余部分,并继续进行下一次迭代,这将再次提示用户输入运算符。

You could get the function calculate() to call itself, here's how:您可以让 function 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()

Very thorough code by the way, great work!顺便说一句,代码非常详尽,干得好!

print(" Welcome to Calculator!") print("欢迎使用计算器!")

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

user_instructions =(''' Instructions: user_instructions =(''' 说明:

Type in a number, then press Enter.输入一个数字,然后按 Enter。 Type in an available Operator, followed by Enter.键入可用的运算符,然后按 Enter。 Type in another number, then press Enter.''')输入另一个数字,然后按 Enter。''')

def instructions(): print(user_instructions) def 指令():打印(用户指令)

instructions()指示()

operator_list =(''' Below is the list of available operators: operator_list =(''' 下面是可用运算符的列表:

  • for Addition加法
  • for Subtraction / for Division减法/除法
  • for Multiplication ^ for exponents r for root % for modulus''')乘法 ^ 指数 r 根 % 模数''')

op_list=['+','-','/','*','^','r','%'] op_list=['+','-','/','*','^','r','%']

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

while True:
    try:
       num1 = float(input("Please enter a number: "))
       break
    except ValueError:
        print("Invalid input. Please try again...")
        print("\n********************************************************************\n")

    
while True:
    try:
       op = input("Please enter an operator: ")
       if op not in op_list:
           print("Invalid input. Please try again...")
           print("\n********************************************************************\n")
           continue
       break 
    except ValueError:
        print("Invalid input. Please try again...")
        

while True:
    try:
       num2 = float(input("Please enter another number: "))
       break
    except ValueError:
        print("Invalid input. Please try again...")
        print("\n********************************************************************\n")

        

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

calculate()计算()

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

def again(): calc_again = input(''' Would you like to calculate again? Please type Y for YES or N for No. ''') def again(): calc_again = input(''' 你想再计算一次吗?请输入 Y 表示是或 N 表示否。''')

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")
    print("\n********************************************************************\n")
    print("\n")
    again()
    print("\n********************************************************************\n")
    calculate()

again()再次()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM