I'm trying to build a calculator, and I'm a bit stuck on how to overwrite the user input with a new value using the same variable. What I am wanting is when greeted at the menu, when the user enters "5" it prompts for a new input for the variables "num1" and "num2". I have a feeling this is extremely easy to do but for some reason i'm stuck.
I have tried the normal - num1 = int(input("Enter new first number: )) and so on within the correct elif, but I get:
UnboundLocalError: local variable 'num1' referenced before assignment
Here is my code:
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))
def calculate():
print('''The numbers you have selected to calculate are:
{}, and {} \n'''.format(num1, num2))
menu = int(input(''' Main Menu:
1. Addition
2. Subtraction
3. Multiplication
4. Division
5. Enter new numbers
6. Exit\n '''))
if menu == 1:
add = addition(num1, num2)
print("{} + {} = {}".format(num1, num2, add))
elif menu == 2:
sub = subtract(num1, num2)
print("{} - {} = {}".format(num1, num2, sub))
elif menu == 3:
multi = multiply(num1, num2)
print("{} x {} = {}".format(num1, num2, multi))
elif menu == 4:
div = divide(num1, num2)
print("{} / {} = {}".format(num1, num2, div))
elif menu == 5:
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))
elif menu == 6:
print("Exiting...")
else:
print("You have not entered a valid input.")
rerun()
The problem with your code is that the num1 and num2 variables are not defined inside the function calculate. So, when you try to access num1 inside the function, it will throw an error.
def calculate():
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))
print('''The numbers you have selected to calculate are:
{}, and {} \n'''.format(num1, num2))
menu = int(input(''' Main Menu:
1. Addition
2. Subtraction
3. Multiplication
4. Division
5. Enter new numbers
6. Exit\n '''))
if menu == 1:
add = addition(num1, num2)
print("{} + {} = {}".format(num1, num2, add))
elif menu == 2:
sub = subtract(num1, num2)
print("{} - {} = {}".format(num1, num2, sub))
elif menu == 3:
multi = multiply(num1, num2)
print("{} x {} = {}".format(num1, num2, multi))
elif menu == 4:
div = divide(num1, num2)
print("{} / {} = {}".format(num1, num2, div))
elif menu == 5:
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))
elif menu == 6:
print("Exiting...")
else:
print("You have not entered a valid input.")
rerun()
calculate()
You can also try and make the variables num1 and num2 global.
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))
def calculate():
global num1, num2
print('''The numbers you have selected to calculate are:
{}, and {} \n'''.format(num1, num2))
menu = int(input(''' Main Menu:
1. Addition
2. Subtraction
3. Multiplication
4. Division
5. Enter new numbers
6. Exit\n '''))
if menu == 1:
add = addition(num1, num2)
print("{} + {} = {}".format(num1, num2, add))
elif menu == 2:
sub = subtract(num1, num2)
print("{} - {} = {}".format(num1, num2, sub))
elif menu == 3:
multi = multiply(num1, num2)
print("{} x {} = {}".format(num1, num2, multi))
elif menu == 4:
div = divide(num1, num2)
print("{} / {} = {}".format(num1, num2, div))
elif menu == 5:
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))
elif menu == 6:
print("Exiting...")
else:
print("You have not entered a valid input.")
rerun()
calculate()
You could also pass the variables as parameters to the function calculate
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))
def calculate(num1, num2):
print('''The numbers you have selected to calculate are:
{}, and {} \n'''.format(num1, num2))
menu = int(input(''' Main Menu:
1. Addition
2. Subtraction
3. Multiplication
4. Division
5. Enter new numbers
6. Exit\n '''))
if menu == 1:
add = addition(num1, num2)
print("{} + {} = {}".format(num1, num2, add))
elif menu == 2:
sub = subtract(num1, num2)
print("{} - {} = {}".format(num1, num2, sub))
elif menu == 3:
multi = multiply(num1, num2)
print("{} x {} = {}".format(num1, num2, multi))
elif menu == 4:
div = divide(num1, num2)
print("{} / {} = {}".format(num1, num2, div))
elif menu == 5:
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))
elif menu == 6:
print("Exiting...")
else:
print("You have not entered a valid input.")
rerun()
calculate(num1, num2)
Related
# Python program for simple calculator
# Function to add two numbers
def add(num1, num2):
return num1 + num2
# Function to subtract two numbers
def subtract(num1, num2):
return num1 - num2
# Function to multiply two numbers
def multiply(num1, num2):
return num1 * num2
# Function to divide two numbers
def divide(num1, num2):
return num1 / num2
print("Welcome, please choose the operation:\n" \
"1. Addition\n" \
"2. Subtraction\n" \
"3. Multiplication\n" \
"4. Division\n" \
"5. Exit\n")`enter code here`
# Take input from the user
select = int(input("Please, Type the choice:"))
number_1 = int(input("Enter number 1: "))
number_2 = int(input("Enter number 2: "))
if select == 1:
print(number_1, "+", number_2, "=",
add(number_1, number_2))
elif select == 2:
print(number_1, "-", number_2, "=",
subtract(number_1, number_2))
elif select == 3:
print(number_1, "*", number_2, "=",
multiply(number_1, number_2))
elif select == 4:
if number_2 ==0:
print('You cannot divide by zero')
else:
print(number_1, "/", number_2, "=",
divide(number_1, number_2))
elif select == 5:
print("Thanks and goodbye")
Effective Solution
Menu operations are performed in the while loop defined within the main() method.
import operator
def main():
while True:
print("1. Addition\n2. Subtraction\n3. Multiplication\n4. Division\n5. Exit\n")
select = int(input("Please, Type the choice:"))
if select >= 1 and select <= 4:
number_1 = int(input("Enter number 1: "))
uOperator = input("Enter operation type: ")
number_2 = int(input("Enter number 2: "))
ops = { '+' : operator.add, '-' : operator.sub, '*' : operator.mul, '/' : operator.truediv }
print(number_1, uOperator, number_2, "=", ops[uOperator](number_1, number_2))
elif select == 5:
print("Thanks and goodbye!")
break
else:
print("You have entered incorrectly! Please select the range [1, 5]")
if __name__ == "__main__":
main()
Usage of the program:
Enter number 1: 3
Enter operation type: *
Enter number 2: 5
3 * 5 = 15
Solution with Current Approach
def add(num1, num2):
return num1 + num2
def subtract(num1, num2):
return num1 - num2
def multiply(num1, num2):
return num1 * num2
def divide(num1, num2):
return num1 / num2
def main():
while True:
print("1. Addition\n2. Subtraction\n3. Multiplication\n4. Division\n5. Exit\n")
select = int(input("Please, Type the choice:"))
if select >= 1 and select <= 4:
number_1 = int(input("Enter number 1: "))
number_2 = int(input("Enter number 2: "))
if select == 1:
print(number_1, "+", number_2, "=", add(number_1, number_2))
elif select == 2:
print(number_1, "-", number_2, "=", subtract(number_1, number_2))
elif select == 3:
print(number_1, "*", number_2, "=", multiply(number_1, number_2))
elif select == 4:
if number_2 ==0:
print('You cannot divide by zero')
else:
print(number_1, "/", number_2, "=", divide(number_1, number_2))
elif select == 5:
print("Thanks and goodbye!")
break
else:
print("You have entered incorrectly! Please select the range [1, 5]")
if __name__ == "__main__":
main()
def add(num1, num2):
return num1 + num2
def sub(num1, num2):
return num1 - num2
def mul(num1, num2):
return num1 * num2
def div(num1, num2):
return num1 / num2
print(f"Select Operation")
print(f"1) Addition")
print(f"2) Subtraction")
print(f"3) Multiplication")
print(f"4) Divition")
while True:
choice = input("Enter choice (1, 2, 3, or 4): ")
if choice in ('1', '2', '3', '4'):
num1 = float(input("Enter the first number: "))
num2 = float(input("Enter the second number: "))
if choice == '1':
print(f" {num1} + {num2} = ", add(num1, num2))
elif choice == '2':
print(f" {num1} - {num2} = ", subtract(num1, num2))
elif choice == '3':
print(f" {num1} * {num2} = ", multiply(num1, num2))
elif choice == '4':
print(f" {num1} / {num2} = ", divide(num1, num2))
next_calculation = input("Let's do another calculation? (yes/no): ")
if next_calculation == "no":
break
else:
print("Invalid Input")
I need help understanding why the break after if next_calculation == "no": always spits out SyntaxError: 'break' outside loop. Please help me fix it so the simple app will run.
Python blocks are designated by indentation, and your break command is not inside the while loop.
To fix this, you need to indent the entire if/else block so it is inside the while loop.
while True:
choice = input("Enter choice (1, 2, 3, or 4): ")
if choice in ('1', '2', '3', '4'):
num1 = float(input("Enter the first number: "))
num2 = float(input("Enter the second number: "))
if choice == '1':
print(f" {num1} + {num2} = ", add(num1, num2))
elif choice == '2':
print(f" {num1} - {num2} = ", subtract(num1, num2))
elif choice == '3':
print(f" {num1} * {num2} = ", multiply(num1, num2))
elif choice == '4':
print(f" {num1} / {num2} = ", divide(num1, num2))
next_calculation = input("Let's do another calculation? (yes/no): ")
if next_calculation == "no":
break
else:
print("Invalid Input")
This question already has answers here:
How to test multiple variables for equality against a single value?
(31 answers)
Why does "a == x or y or z" always evaluate to True? How can I compare "a" to all of those?
(8 answers)
Closed 1 year ago.
Hello all genius fellows, please find below code. code is running excellent till end but in the end while it ask for Y/N after 1st iteration no matter what I press its breaking the statement and exiting the loop.
class simpleCalculator:
def addition(self, num1, num2):
return num1+num2
def sub(self, num1, num2):
return num1-num2
def multiplication(self, num1, num2):
return num1*num2
def division(self, num1, num2):
return num1/num2
a = simpleCalculator()
print("Enter your choice: ")
print(''' 1.Addition
2.Subtraction
3.Multiplication
4.Division''')
while True:
choice = int(input("Enter your choice(1/2/3/4): "))
if choice in (1, 2, 3, 4):
num1 = int(input("Enter 1st number: "))
num2 = int(input("Enter 2nd number: "))
if choice == 1:
print(f"Addition of {num1} & {num2} is {a.addition(num1,num2)}")
elif choice == 2:
print(f"Subtraction of {num1} & {num2} is {a.sub(num1,num2)}")
elif choice == 3:
print(
f"Multiplication of {num1} & {num2} is {a.multiplication(num1,num2)}")
elif choice == 4:
print(f"Division of {num1} & {num2} is {a.division(num1,num2)}")
next_cal = input("You want more calculation(Y/N): ")
if next_cal == "N" or "n":
print("****** Thank you for using world's best calculator ******")
break
else:
print("Invalid Choice")
class simpleCalculator:
def addition(self, num1, num2):
return num1+num2
def sub(self, num1, num2):
return num1-num2
def multiplication(self, num1, num2):
return num1*num2
def division(self, num1, num2):
return num1/num2
a = simpleCalculator()
print("Enter your choice: ")
print("1.Addition \n 2.Subtraction \n 3.Multiplication \n 4.Division")
while True:
choice = int(input("Enter your choice(1/2/3/4): "))
if choice in (1, 2, 3, 4):
num1 = int(input("Enter 1st number: "))
num2 = int(input("Enter 2nd number: "))
if choice == 1:
print(f"Addition of {num1} & {num2} is {a.addition(num1,num2)}")
elif choice == 2:
print(f"Subtraction of {num1} & {num2} is {a.sub(num1,num2)}")
elif choice == 3:
print(
f"Multiplication of {num1} & {num2} is {a.multiplication(num1,num2)}")
elif choice == 4:
print(f"Division of {num1} & {num2} is {a.division(num1,num2)}")
next_cal = input("You want more calculation(Y/N): ")
if next_cal == "N" or "n":
print("****** Thank you for using world's best calculator ******")
else:
print("Invalid Choice")
Hello I am having a trouble while doing my simple calculator code :D
def cal():
while True:
print ("welcome to my calculator!")
print("choose an operation")
op = input(" +, - ,/ ,*")
if op == "+":
num1 = float(input("enter your first number:"))
num2 = float(input("enter your second number:"))
print(str(num1 + num2)
elif op == "/":
num1 = float(input("enter your first number:"))
num2 = float(input("enter your second number:"))
print(str(num1 / num2)
else:
break
cal()
When ever I run the code it says invalid syntax at the elif
what is wrong here?
You never closed the bracket on the print function. Same goes for the other if statement. You should use indentation of 4 spaces in the future, too.
if op == "+":
num1 = float(input("enter your first number:"))
num2 = float(input("enter your second number:"))
print(str(num1 + num2))
You missed a bunch of brackets. If you want to take your program further use this as a model:
# This function adds two numbers
def add(x, y):
return x + y
# This function subtracts two numbers
def subtract(x, y):
return x - y
# This function multiplies two numbers
def multiply(x, y):
return x * y
# This function divides two numbers
def divide(x, y):
return x / y
print("Select operation.")
print("1.Add")
print("2.Subtract")
print("3.Multiply")
print("4.Divide")
# Take input from the user
choice = input("Enter choice(1/2/3/4):")
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))
if choice == '1':
print(num1,"+",num2,"=", add(num1,num2))
elif choice == '2':
print(num1,"-",num2,"=", subtract(num1,num2))
elif choice == '3':
print(num1,"*",num2,"=", multiply(num1,num2))
elif choice == '4':
print(num1,"/",num2,"=", divide(num1,num2))
else:
print("Invalid input")
I am trying to build a simple calculator. I just want the user to enter two numbers and an operation, then for the calculation to be shown, then to loop back to entering two numbers again. If the user enters an operation that is not recognized I want to loop back to 'enter operation'.
Why is this not working:
def add (a,b):
return a + b
def minus (a,b):
return a - b
def multi (a,b):
return a * b
def div (a,b):
return a / b
def numPic():
num1 = int(input("Type a number: "))
num2 = int(input("Type another number: "))
def opPic():
op = input("Type an operation (add,minus,multi,div):" )
if op == "add":
print (add (num1,num2))
elif (op == "minus"):
print (minus(num1,num2))
elif (op == "multi"):
print (mulit(num1,num2))
elif (op == "div"):
print (div(num1,num2))
else :
print ("operation not recognised")
opPic ()
print ("Hello User")
numPic()
opPic()
You have a few bugs. First, num1 and num2 are local to numPic--not
global. So you need to return them to the caller, and the caller has to pass
them to opPic():
def numPic():
num1 = int(input("Type a number: "))
num2 = int(input("Type another number: "))
return num1, num2
def opPic(num1, num2):
op = input("Type an operation (add,minus,multi,div):" )
if op == "add":
print (add (num1,num2))
elif (op == "minus"):
print (minus(num1,num2))
elif (op == "multi"):
print (mulit(num1,num2))
elif (op == "div"):
print (div(num1,num2))
else :
print ("operation not recognised")
opPic (num1, num2)
num1, num2 = numPic()
opPic (num1, num2)
To make it loop-based, you could do something like:
def opPic(num1, num2):
while True:
op = input("Type an operation (add,minus,multi,div):" )
if op == "add":
print (add (num1,num2))
elif (op == "minus"):
print (minus(num1,num2))
elif (op == "multi"):
print (mulit(num1,num2))
elif (op == "div"):
print (div(num1,num2))
else :
print ("operation not recognised")
continue
break
Hopefully, you can figure out the other bit on your own, as this looks like a school assignment.
The num1 and num2 you define in numPic are local to that function. You need to return them and pass them to the opPic function for them to be used.
def numPic():
num1 = int(input("Type a number: "))
num2 = int(input("Type another number: "))
return num1, num2
def opPic(num1, num2):
#the same code as before
#except changing opPic() to opPic(num1, num2)
print ("Hello User")
num1, num2 = numPic()
opPic(num1, num2)
There are better ways of doing what you seem to be aiming for though. You haven't actually used a loop and have used recursion instead.