2

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()
Community
  • 1
  • 1
instantity
  • 33
  • 4
  • Does this answer your question? [This python code is not solving equations](https://stackoverflow.com/questions/39908815/this-python-code-is-not-solving-equations) – Jan Matějka Jul 31 '20 at 01:07

3 Answers3

1

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.

ReedGhost
  • 111
  • 3
  • I get a never ending loop after adding the code ReedGhost suggested. The program keeps asking for operator inout even if a correct one is entered. while True: try: op = input("Enter an operator: ") if(op != "+" or op != "-"): continue num2 = float(input("Enter another number: ")) break except ValueError: print("Invalid input. Please try again. – instantity Jul 31 '20 at 23:52
  • Hey all! I was able to resolve my issue by making a couple adjustments including adding another variable for the list of operators and calling it within the loop for op. Then I added another while loop for the num2 variable. The code is below: – instantity Aug 01 '20 at 18:23
1

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!

JimmyCarlos
  • 1,934
  • 1
  • 10
  • 24
0

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

instantity
  • 33
  • 4