Why I'm getting out of the loop? [duplicate] - python

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

Related

How to fix SyntaxError: 'break' outside loop in Python app

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

Overwrite previous user inputted variable with new user input

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)

stuck with a simple python program "elif"

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

NameError: name '' is not defined with multiple define functions

I just want to start off by saying I know this code is wrong, I'm just testing
this is meant to be a calculator, as you may be able to see from the code I am trying to make the number they end with e.g.
10 + 10 = 20, they will keep the number 20 and can carry on with 20, I want to keep repeating that option
Code:
def add(num1, num2):
return num1 + num2
def mul(num1, num2):
return num1 * num2
def sub(num1, num2):
return num1 - num2
def div(num1, num2):
return num1 / num2
def main():
operation = input("Do you want to(+,-,*,/): ")
if(operation != "+" and operation != "-" and operation != "*" and operation != "/"):
print("That is an invalid operation")
else:
num1 = float(input("choose a number: "))
num2 = float(input("Choose another number: "))
if(operation == "+"):
answer = (add(num1, num2))
print(answer)
elif(operation == "-"):
answer = (sub(num1, num2))
print(answer)
elif(operation == "*"):
answer = (mul(num1, num2))
print(answer)
elif(operation == "/"):
answer = (div(num1, num2))
print(answer)
else:
print("Syntax error!")
def multiple(multiple):
multiple = input("would you like to carry the number(Y or N): ")
if(multiple == "Y" or multiple == "y"):
carry = input("(+,-,*,/): ")
num3 = int(input("choose a number: "))
if(carry == "+"):
print(answer + num3)
elif(carry == "-"):
print(answer - num3)
elif(carry == "*"):
print(answer * num3)
elif(carry == "/"):
print(answer / num3)
else:
print("Syntax Error!")
multiple = True
while multiple == True:
multiple()
choice = input("would you like multiple calculations? (Y or N): ")
while(choice == "y" or choice == "Y"):
main()
multiple()
multiple()
main()
error message:
line 56, in <module>
multiple()
NameError: name 'multiple' is not defined
p.s There may be some indentation errors in this as it pasted strange
You're trying to call the function multiple outside of the scope of the main function while it is only defined in it. Assuming that your indentation is as presented here, you need to move the definition of multiple outside of main so that it can be called.
Additionally, you're defining a variable named multiple which might create some problems. You should change it to something else.
I optimized your code a little and fixed it. It works fine so take a look at it.
def add(num1, num2):
return num1 + num2
def mul(num1, num2):
return num1 * num2
def sub(num1, num2):
return num1 - num2
def div(num1, num2):
return num1 / num2
def main(carry):
operation = input("Do you want to (+,-,*,/): ")
if(operation != "+" and operation != "-" and operation != "*" and operation != "/"):
print("That is an invalid operation")
else:
num1 = float(input("choose a number: "))
if carry == None:
num2 = float(input("Choose another number: "))
else:
num2 = carry
if(operation == "+"):
answer = add(num1, num2)
elif(operation == "-"):
answer = sub(num1, num2)
elif(operation == "*"):
answer = mul(num1, num2)
elif(operation == "/"):
answer = div(num1, num2)
print(answer)
return answer
if input("would you like multiple calculations? (Y or N): ") in ("y", "Y"):
domultiple = True
else:
domultiple = False
carry = None
while 1:
carry = main(carry)
if domultiple:
if input("would you like to carry the number (Y or N): ") in ("n", "N"):
break
else:
break

shortening a calculator in python

I have managed to create a small calculator in Python, but I am trying to shorten the code unsucsessfully. Can anyone help please?
elif queencommand == "/calc addition" :
num1 = input("Enter first number")
num2 = input("Enter second number")
Answer = (int(num1) + int(num2))
input(Answer)
elif queencommand == "/calc subtraction" :
num1 = input("Enter first number")
num2 = input("Enter second number")
Answer = (int(num1) - int(num2))
input(Answer)
elif queencommand == "/calc multiplication" :
num1 = input("Enter first number")
num2 = input("Enter second number")
Answer = (int(num1) * int(num2))
input(Answer)
elif queencommand == "/calc division" :
num1 = input("Enter first number")
num2 = input("Enter second number")
Answer = (int(num1) / int(num2))
input(Answer)
I am not able to do two operations at once either.
Use functions from the operator module or simple functions you define yourself to the calculation work, then map the operation name from the queencommand string to those functions:
import operator
ops = {
'addition': operator.add,
'subtraction': operator.sub,
'multiplication': operator.mul,
'division': operator.truediv
}
if queencommand.startswith("/calc"):
operation = queencommand.partition(' ')[-1]
if operation in ops:
num1 = input("Enter first number")
num2 = input("Enter second number")
Answer = ops[operation](int(num1), int(num2))
operator.add could be replaced by lambda a, b: a + b, etc. if you don't want to use a module for those operations.
Here is a fully fledged calculator. See if it helps:
def multiplication():
num1 = int(input("First #: "))
num2 = int(input("Second #: "))
ans = num1 * num2
print(ans)
def addition():
num1 = int(input("First #: "))
num2 = int(input("Second #: "))
ans = num1 + num2
print(ans)
def subtraction():
num1 = int(input("First #: "))
num2 = int(input("Second #: "))
ans = num1 - num2
print(ans)
def division():
num1 = int(input("First #: "))
num2 = int(input("Second #: "))
ans = num1 / num2
print(ans)
def Help():
print("""Welcome to Calculator P1!!!
Type "x" for multiplication.
Type "+" for addition.
Type "-" for subtraction.
Type "/" for division.""")
while True:
print("Type 'help' for introduction or instructions")
choice = input("Operator: ")
if choice == "x" or choice == "muliplication":
multiplication()
elif choice == "+" or choice == "addition":
addition()
elif choice == "-" or choice == "subtraction":
subtraction()
elif choice == "/" or choice == "division":
division()
elif choice == "help":
Help()
answer = input('Run again? (y/n): ')
if answer == 'n':
break
elif answer == 'y':
continue
else:
print("""Unrecognized Input.
<<<<RESTARTING PROGRAM>>>>""")
continue

Categories