I have created a calculator in python that can calculate the addition, subtraction, multiplication, division or modulus of two integers. What equation is executed is based on which number is type in from the menu, and I would like the user to be able to go back to the menu after an equation after being asked whether or not to "continue?". Would appreciate any help
print("MENU")
print("1. Add")
print("2. Subtract")
print("3. Multiply")
print("4. Divide")
print("5. Modulous")
menu = input("Enter your choice: ")
if int(menu) == 1:
def additon(number1=int(input("Enter first number: ")), number2=int(input("Enter second number: "))):
return(number1 + number2)
answer1 = additon()
print("Result:", answer1)
if int(menu) == 2:
def subtraction(number1=int(input("Enter first number: ")), number2=int(input("Enter second number: "))):
return(number1 - number2)
answer2 = subtraction()
print("Result: ", answer2)
if int(menu) == 3:
def multiplication(number1=int(input("Enter first number: ")), number2=int(input("Enter second number: "))):
return(number1 * number2)
answer3 = multiplication()
print("Result: ", answer3)
if int(menu) == 4:
def division(number1=int(input("Enter first number: ")), number2=int(input("Enter second number: "))):
return(number1 / number2)
answer4 = division()
print("Result: ", answer4)
if int(menu) == 5:
def modulus(number1=int(input("Enter first number: ")), number2=int(input("Enter second number: "))):
return(number1 % number2)
answer5 = modulus()
print("Result: ", answer5)
if int(menu) != 1 or 2 or 3 or 4 or 5:
print("Not a valid option")
First define your functions once at the top of the program, you are
currently defining functions (eg. addition) inside if statements
put all your main code in a 'forever' (while True:) loop so that each time through the loop it prints out the menu, accepts input, and displays the results then returns to the top of the loop to do it all over again
when you read user input, before converting it to an integer, add code to check if the user typed something like 'q' (for quit) and if they did then use break to take you out of the 'forver' loop and end the program
here's a skeleton version:
def print_menu():
"""print the menu as show in your code"""
def addition():
"""your addition function"""
...
def subtraction():
"""your subtraction function"""
...
# etc
while True: # 'forever' loop
print_menu()
resp = input("your choice? ")
if resp == 'q': # user wants to quit
break # so break out of forever loop
resp = int(resp) # change your resp to an integer
if resp == 1:
answer = addition()
elif resp == 2:
answer = subtraction()
elif resp == 3:
answer = multiplication()
elif resp == 4:
answer = division()
else:
print("unknown choice, try again")
continue # go back to top of loop
print("The Answer Is", answer)
An answer has already been accepted for this but I'll throw this out there anyway.
This kind of exercise is ideally suited to a table-driven approach.
The operations are trivial so rather than define discrete functions a lambda will suffice
Define a dictionary where we look up and validate the user's option.
Get the user input and carry out sanity checks.
We end up with just 2 conditional checks - one of which is merely concerned with quitting the [potentially] infinite loop.
CONTROL = {'1': lambda x, y: x + y,
'2': lambda x, y: x - y,
'3': lambda x, y: x * y,
'4': lambda x, y: x / y,
'5': lambda x, y: x % y}
while True:
print("MENU")
print("1. Add")
print("2. Subtract")
print("3. Multiply")
print("4. Divide")
print("5. Modulus")
option = input('Select an option or q to quit: ')
if option and option in 'qQ':
break
if option in CONTROL:
x = input('Input X: ')
y = input('Input Y: ')
try:
result = CONTROL[option](int(x), int(y))
print(f'Result={result}')
except ValueError:
print('Integer values only please')
except ZeroDivisionError:
print("Can't divide by zero")
else:
print('Invalid option')
print()
Wrap your code in a while loop. The following code should work.
def additon(number1, number2):
return (number1 + number2)
def subtraction(number1, number2):
return(number1 - number2)
def multiplication(number1, number2):
return(number1 * number2)
def division(number1, number2):
return(number1 / number2)
def modulus(number1, number2):
return(number1 % number2)
x = True
while (x):
print("MENU")
print("1. Add")
print("2. Subtract")
print("3. Multiply")
print("4. Divide")
print("5. Modulous")
menu = input("Enter your choice: ")
if int(menu) == 1:
answer1 = additon(number1=int(input("Enter first number: ")),
number2=int(input("Enter second number: ")))
print("Result:", answer1)
elif int(menu) == 2:
answer2 = subtraction(number1=int(input("Enter first number: ")),
number2=int(input("Enter second number: ")))
print("Result: ", answer2)
elif int(menu) == 3:
answer3 = multiplication(number1=int(input("Enter first number: ")),
number2=int(input("Enter second number: ")))
print("Result: ", answer3)
elif int(menu) == 4:
answer4 = division(number1=int(input("Enter first number: ")),
number2=int(input("Enter second number: ")))
print("Result: ", answer4)
elif int(menu) == 5:
answer5 = modulus(number1=int(input("Enter first number: ")),
number2=int(input("Enter second number: ")))
print("Result: ", answer5)
elif int(menu) < 1 or int(menu) > 5:
print("Not a valid option")
go_again = input("Would you like to go again (y/n): ")
if (go_again.lower()=="n"):
x = False
else:
continue
Related
Ok so I am very new to Python and I recently took on the challenge of creating a very simple calculator.
It works completely fine but I want to add a option to restart and go back to the main menu area rather than restarting the program entirely. How could this be done?
here is the code that i have so far
from math import sqrt
import time
print("Welcome to Calculator")
print(" #1 Add \n #2 Subtract \n #3 Multiply \n #4 Divide \n #5 Square Root")
option = input("Select one #: ")
if option == "1":
print("Addition:")
num1 = input("Enter first Number: ")
num2 = input("Enter Second Number: ")
result = float(num1) + float(num2)
print("The answer is: ", result)
elif option == "2":
print("Subtraction:")
num1 = input("Enter first Number: ")
num2 = input("Enter Second Number: ")
result = float(num1) - float(num2)
print("The answer is: ", result)
elif option == "3":
print("Multiplication:")
num1 = input("Enter first Number: ")
num2 = input("Enter Second Number: ")
result = float(num1) * float(num2)
print("The answer is: ", result)
elif option == "4":
print("Division:")
num1 = input("Enter first Number: ")
num2 = input("Enter Second Number: ")
result = float(num1) / float(num2)
print("The answer is: ", result)
elif option == "5":
print("Square Root:")
num1 = input("Enter Number: ")
result = sqrt(float(num1))
print("The answer is: ", result)
I tried the adding While True to the program but I was not able to figure out how that works.
Wrapping your whole code in a while True loop would work but you need to write an if statement at the end in order to exit the infinite loop. Here's the working code:
from math import sqrt
import time
while True:
print("Welcome to Calculator")
print(" #1 Add \n #2 Subtract \n #3 Multiply \n #4 Divide \n #5 Square Root")
option = input("Select one #: ")
if option == "1":
print("Addition:")
num1 = input("Enter first Number: ")
num2 = input("Enter Second Number: ")
result = float(num1) + float(num2)
print("The answer is: ", result)
elif option == "2":
print("Subtraction:")
num1 = input("Enter first Number: ")
num2 = input("Enter Second Number: ")
result = float(num1) - float(num2)
print("The answer is: ", result)
elif option == "3":
print("Multiplication:")
num1 = input("Enter first Number: ")
num2 = input("Enter Second Number: ")
result = float(num1) * float(num2)
print("The answer is: ", result)
elif option == "4":
print("Division:")
num1 = input("Enter first Number: ")
num2 = input("Enter Second Number: ")
result = float(num1) / float(num2)
print("The answer is: ", result)
elif option == "5":
print("Square Root:")
num1 = input("Enter Number: ")
result = sqrt(float(num1))
print("The answer is: ", result)
restart = input("Do you want to restart the program? (yes/no) ")
if restart.lower() != "yes":
break
You can add while loop like this:
while True:
option = input("Select one #: ")
if option == "1":
print("Addition:")
...
elif option == "5":
print("Square Root:")
num1 = input("Enter Number: ")
result = sqrt(float(num1))
print("The answer is: ", result)
I would like for the input to remember the first number given to it even if you type something silly on the second input. While right now obviously the loop starts again and asks for both of the inputs again. Is there an easy way to do this?
Calculator
Give a number: 124
Give a number: dwa
This input is invalid.
Give a number: 12
Give a number:
while I would like it to do this:
Calculator
Give first number: 124
Give second number: dwa
This input is invalid.
Give second number: 12
And this is the entire code:
import math
import sys
print("Calculator")
def main():
while True:
try:
kek1 = int(input('Give a number: '))
kek2 = int(input('Give a number: '))
while True:
print('(1) +')
print('(2) -')
print('(3) *')
print('(4) /')
print('(5) sin(number1/number2')
print('(6) cos(number1/number2)')
print('(7) Change numbers')
print('(8) Quit')
print(f'Current numbers are: {kek1} {kek2}')
kaka = input("Please select something (1-6):")
plus = kek1 + kek2
minus = kek1 - kek2
times = kek1 * kek2
divide = kek1 / kek2
sin = math.sin(kek1/kek2)
cos = math.cos(kek1/kek2)
if kaka == "1":
print(f'The result is: {plus}')
if kaka == "2":
print(f'The result is: {minus}')
if kaka == "3":
print(f'The result is: {times}')
if kaka == "4":
print(f'The result is: {divide}')
if kaka == "5":
print(f'The result is: {sin}')
if kaka == "6":
print(f'The result is: {cos}')
if kaka == "7":
kek1 = int(input('Give a number: '))
kek2 = int(input('Give a number: '))
if kaka == "8":
print("Thank you!")
sys.exit(0)
except SystemExit:
sys.exit(0)
except:
print("This input is invalid.")
if __name__=="__main__":
main()
If you have any ideas on how to do this it would be a great help.
Use separate try statements for each input with their own loops
while True:
try:
kek1 = input("First number")
kek1 = int(kek1)
break
except:
print("Invalid")
continue
while True:
try:
kek2 = input("Second number")
kek2 = int(kek2)
break
except:
print("Invalid")
continue
And then go into the rest of your loop.
Sorry for a brief answer but I'm on my phone :P
instead of using try catch, you may use .isnumeric() :
kek1 = input("First number")
while not kek1.isnumeric() :
print("This input is invalid.")
kek1 = input("First number")
kek1 =int(kek1)
kek2 = input("First number")
while not kek2.isnumeric() :
print("This input is invalid.")
kek2 = input("Second number")
kek2 =int(kek1)
Hello I'm trying to add two natural numbers and I wanted the program to continue and have an option to break.
This is my code:
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number:"))
sum = num1 + num2
if (sum % 2) == 0:
print(sum, "is Even")
else:
print(sum," is Odd")
You can do this using a while loop. So for example:
while True:
play = input("Do you want to play (type no to stop)?")
if play == 'no':
break
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number:"))
sum = num1 + num2
if (sum % 2) == 0:
print(sum, "is Even")
else:
print(sum," is Odd")
Put all of this code in a loop and add option to continue/ break before taking input from the user.
while(True):
option = int(input("Enter 0 to break. Else, continue")
if option == 0:
break
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number:"))
sum = num1 + num2
if (sum % 2) == 0:
print(sum, "is Even")
else:
print(sum," is Odd")
print('entry "quit" when you want toe terminate the program')
# infinite loop
while 1:
# input validation
try:
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number:"))
except ValueError:
print('Please entry a number')
print()
# continue would restart the while loop
continue
if(num1 == 'quit' or num2 == 'quit'):
# break will terminate the while loop
break
sum = num1 + num2
if (sum % 2) == 0:
print(sum, "is Even")
else:
print(sum," is Odd")
You can always nest these statements in a while loop and break on some condition.
def process_results():
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number:"))
sum = num1 + num2
if (sum % 2) == 0:
print(sum, "is Even")
else:
print(sum,"is Odd")
def get_choice():
print("Enter R to run program or Q to quit:")
choice = input()
return choice
def main():
while(True):
choice = get_choice()
if choice == 'R' or choice == 'r':
process_results()
elif choice == 'Q' or choice == 'q':
print("This program has quit")
else:
print("You must enter R to run program or Q to quit")
main()
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")
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