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')
Related
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")
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()
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 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
This question already has answers here:
How do I restart a program based on user input?
(6 answers)
Closed 4 years ago.
This is a simple calculator i wrote but after finishing it won't restart the application
this is my code:
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 from the list bellow which oporation you want the calculator to do.")
print("A.Add")
print("S.Subtract")
print("M.Multiply")
print("D.Divide")
choice = input("Enter choice(a/s/m/d):")
if choice != 'a' and choice != 's' and choice != 'm' and choice != 'd':
print (" the letter you intered is not in our lists!")
num1 = int(input("Enter an interger as your first number: "))
num2 = int(input("Enter an integer as second number: "))
if choice == 'a':
print(num1,"+",num2,"=", add(num1,num2))
elif choice == 's':
print(num1,"-",num2,"=", subtract(num1,num2))
elif choice == 'm':
print(num1,"*",num2,"=", multiply(num1,num2))
elif choice == 'd':
print(num1,"/",num2,"=", divide(num1,num2))
else:
print("Invalid input")
input("press enter to close")
when its finished i want it to ask the user if they want to restart or not . i used different while looping its not working.
Just loop until the user wants to quit:
def main():
print('Select from the list below which operation you want the calculator to do.')
print("A.Add")
print("S.Subtract")
print("M.Multiply")
print("D.Divide")
while True:
choice = input("Enter choice(a/s/m/d) or q to quit:")
if choice not in {"a", "s", "m", "d","q"}:
print (" the letter you entered is not in our lists!")
continue # if invalid input, ask for input again
elif choice == "q":
print("Goodbye.")
break
num1 = int(input("Enter an integer as your first number: "))
num2 = int(input("Enter an integer as second number: "))
if choice == 'a':
print("{} + {} = {}".format(num1, num2, add(num1, num2)))
elif choice == 's':
print("{} - {} = {}".format(num1, num2, subtract(num1, num2)))
I used str.format to print your output, if choice not in {"a", "s", "m", "d","q"} uses in to test for membership replacing the long if statement.
You might want to wrap the int input inside a try/except to avoid your program crashing if the user does not enter the correct input.
try:
num1 = int(input("Enter an interger as your first number: "))
num2 = int(input("Enter an integer as second number: "))
except ValueError:
continue
If you want to do it like the example in your comment:
def main():
print('Select from the list below which operation you want the calculator to do.')
print("A.Add")
print("S.Subtract")
print("M.Multiply")
print("D.Divide")
while True:
choice = raw_input("Enter choice(a/s/m/d)")
if choice not in {"a", "s", "m", "d","q"}:
print (" the letter you entered is not in our lists!")
continue
num1 = int(input("Enter an integer as your first number: "))
num2 = int(input("Enter an integer as second number: "))
if choice == 'a':
print("{} + {} = {}".format(num1, num2, add(num1, num2)))
elif choice == 's':
print("{} - {} = {}".format(num1, num2, subtract(num1, num2)))
inp = input("Enter 1 to play again or 2 to exit")
if inp == "1":
main()
else:
print("thanks for playing")
break
Instead of this:
if choice != 'a' and choice != 's' and choice != 'm' and choice != 'd' and choice != 'e':
print (" the letter you intered is not in our lists!")
else:
num1 = int(input("Enter an interger as your first number: "))
num2 = int(input("Enter an integer as second number: "))
Use this:
if choice != 'a' and choice != 's' and choice != 'm' and choice != 'd' and choice != 'e':
print (" the letter you intered is not in our lists!")
elif choice==e:
print("goodbye")
break
else:
num1 = int(input("Enter an interger as your first number: "))
num2 = int(input("Enter an integer as second number: "))
You'll need to wrap the part that's processing user input in a while loop. You'll also need an option to break that while loop in your selection process. I added an input value of e that handles exiting the loop. Your first if statement and the else statement at the end were redundant, so I switched them around a little as well.
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
while True:
print("Select from the list bellow which oporation you want the calculator to do.")
print("A.Add")
print("S.Subtract")
print("M.Multiply")
print("D.Divide")
print("E.Exit")
choice = input("Enter choice(a/s/m/d/e):")
if choice != 'a' and choice != 's' and choice != 'm' and choice != 'd' and choice != 'e':
print (" the letter you intered is not in our lists!")
else:
num1 = int(input("Enter an interger as your first number: "))
num2 = int(input("Enter an integer as second number: "))
if choice == 'a':
print(num1,"+",num2,"=", add(num1,num2))
elif choice == 's':
print(num1,"-",num2,"=", subtract(num1,num2))
elif choice == 'm':
print(num1,"*",num2,"=", multiply(num1,num2))
elif choice == 'd':
print(num1,"/",num2,"=", divide(num1,num2))
elif choice == 'e':
print("Goodbye")
break