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")
Related
Python - Reset button calculator and other issues
This is a python calculator. I developed a part here. but, In this calculator, when the user enters two wrong numbers or one wrong operator, the reset function is given by $ + enter. How to add reset capability to code?
How to fix it?
Program make a simple calculator
# 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
# This function uses to power
def power(x, y):
return x**y
# This function uses for the remainder
def remainder (x, y):
return x % y
print("Please select the operation.")
print("1:Add")
print("2:Subtract")
print("3:Multiply")
print("4:Divide")
print("5:Power")
print("6:remainder")
print("7.Terminate")
print("8.Reset")
while True:
# take input from the user
choice = input("Enter choice(1/2/3/4/5/6): ")
# check if choice is one of the four options
if choice in ('1', '2', '3', '4','5' ,'6'):
num1 = float(input("Enter first number: "))
num2 = float(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))
elif choice == '5':
print(num1, "**", num2, "=", power(num1, num2))
elif choice == '6':
print(num1, "%", num2, "=", remainder(num1, num2))
elif choice == '7':
print(num1 , "#", num2, "=", terminate(num1,num2))
next_calculation = input("Let's do next calculation? (yes/no): ")
if next_calculation == "no":
print("Thank you")
#this funtion uses to optimize the code [ select_op(choice) funtion also used here ]
def find(choice):
if reset_operand == "yes":
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
select_op(choice)
elif reset_operand == "no":
select_op(choice)
# take input from the user
choice = input("Enter choice(1/2/3/4/5/6): ")
if choice in ('1', '2', '3', '4', '5', '6'):
reset_operation = input("Do you need to change the operation? (yes/no): ")
if reset_operation == "yes":
choice = input("Enter again choice(1/2/3/4/5/6): ")
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
reset_operand = input("Do you need to change the reset_operand? (yes/no): ")
if reset_operation == "no":
if choice in ('1', '2', '3', '4', '5', '6'):
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
reset_operand = input("Do you need to change the reset_operand? (yes/no): ")
find(choice)
else:
print("Unrecongnized operation !")
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")
I am building a calculator and I want to know if i can make num2 input be skipped when "root" option is chosen.
This is my code:
num1 = float(input("Enter a number: "))
op = input("Enter a operator: ")
if op not in operators:
print("Invalid operator")
start()
num2 = float(input("Enter a number: "))
if op == "+":
print(num1 + num2)
elif op == "-":
print(num1 - num2)
elif op == "*":
print(num1 * num2)
elif op == "/":
print(num1 / num2)
elif op == "^":
print(pow(num1, num2))
elif op == "root":
print(math.sqrt(num1))
restart = input("Continue?: ")
if restart == "yes":
start()
else:
sys.exit(0)
I want this to get ignored:
num2 = float(input("Enter a number: "))
When this is the case:
elif op == "root":
print(math.sqrt(num1))
Put the second number input statement behind an if:
op = input("Enter a operator: ")
if op != "root":
num2 = float(input("Enter a number: "))
To do this, you could do:
if op != "root":
num2 = float(input("Enter a number: "))
This would skip the num2 input if op == "root"
There can be many different ways. One suggestion would be as below.
num1 = float(input("Enter a number: "))
op = input("Enter a operator: ")
# HERE
if op != "root" and op in operators:
num2 = float(input("Enter a number: "))
elif op not in operators:
print("Invalid operator")
start()
if op == "+":
print(num1 + num2)
elif op == "-":
print(num1 - num2)
elif op == "*":
print(num1 * num2)
elif op == "/":
print(num1 / num2)
elif op == "^":
print(pow(num1, num2))
elif op == "root":
print(math.sqrt(num1))
restart = input("Continue?: ")
if restart == "yes":
start()
else:
sys.exit(0)
or
# HERE
if op in operators:
if op != "root":
num2 = float(input("Enter a number: "))
else:
print("Invalid operator")
start()
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)
Need to add a loop to my calculator by giving the user an option to restart the calculator by putting the code in a while loop with the condition that the input from user should be, 'y' or 'Y'.
def add(x, y):
return x + y
def subtract(x, y):
return x - y
def multiply(x, y):
return x * y
def divide(x, y):
return x / y
print("Select operation.")
print("1.Add")
print("2.Subtract")
print("3.Multiply")
print("4.Divide")
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")
Just add somethings to Alex's post
cont = "y"
while cont.lower() == "y":
print("Select operation\n1.Add\n2.Subtract\n3.Multiply\n4.Divide")
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,"=", (num1 + num2))
elif choice == '2':
print(num1,"-",num2,"=", (num1 - num2))
elif choice == '3':
print(num1,"*",num2,"=", (num1 * num2))
elif choice == '4':
print(num1,"/",num2,"=", (num1 / num2))
else:
print("Invalid input")
cont = input("Continue?y/n:")
if cont == "n":
break
Don't really see what the problem is, you can just use another input statement and check the value in the while loop condition...
cont = "y"
while cont == "y" or cont == "Y":
print("Select operation.")
print("1.Add")
print("2.Subtract")
print("3.Multiply")
print("4.Divide")
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,"=", (num1 + num2))
elif choice == '2':
print(num1,"-",num2,"=", (num1 - num2))
elif choice == '3':
print(num1,"*",num2,"=", (num1 * num2))
elif choice == '4':
print(num1,"/",num2,"=", (num1 / num2))
else:
print("Invalid input")
cont = raw_input("Continue?y/n:")
you can simply modify your code like this
def continue():
resp = input("Continue ? Y/N ")
if resp == "n" or resp == "N":
return False
return True
while True:
print("Select operation.")
print("1.Add")
print("2.Subtract")
print("3.Multiply")
print("4.Divide")
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,"=", (num1 + num2))
elif choice == '2':
print(num1,"-",num2,"=", (num1 - num2))
elif choice == '3':
print(num1,"*",num2,"=", (num1 * num2))
elif choice == '4':
print(num1,"/",num2,"=", (num1 / num2))
else:
print("Invalid input")
if not continue() :
break
you can change the continue function as you like
Here's a while loop example :
Changed
again = "y"
while again:
# ...
#enter your code here
# ...
a = input("do you want to do again (y/Y): ")
if a not in ("y","Y"):
a=""
enter code here
while True:
b = int(input('first num: '))
c = input('operator: ')
d = int(input('second num: '))
if c == '+':
print(b + d)
elif c == '-':
print(b - d)
elif c == '*':
print(b * d)
elif c == '/':
print(b / d)
q = input('do you want to continue?: ')
if q == 'y':
continue
else:
break
Here's another while loop example
menu ="""
0. chose 0 to quit
1. chose 1 to add
2. chose 2 to sub
3. chose 3 to multi
4. chose 4 to div
"""
chose= None
while(chose != 0):
print(menu)
num1 =int(input('first num is: '))
num2 =int(input('second num is: '))
chose= int(input("plz enter your chose: "))
if(chose == 1):
print(num1, " + ",num2," = ",num1+num2)
elif(chose == 2):
print(num1, " - ",num2," = ",num1+num2)
elif(chose == 3):
print(num1, " * ",num2," = ",num1+num2)
elif(chose == 4):
if(num2 == 0):
print("You can not divide by zero")
else:
print(num1, " / ",num2," = ",num1+num2)
else:
print('plz enter a correct option')