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

Viewed 286

First off, I am new to 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. 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. 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. 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? 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()
3 Answers

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.

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.

You could get the function calculate() to call itself, here's how:

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("\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''')

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

def calculate(): 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")

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

again()

Related