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
total = 0
print ("Enter first number")
num1 = input()
print ("Enter 1)Add 2)Minus 3)Multiply 4)Divide")
choice = input()
while True:
print("Wrong Answer Pick Again")
print("Enter 1)Add 2)Minus 3)Multiply 4)Divide")
choice = input()
if choice => 1 and choice =< 4:
break
if choice == 1:
print ('Enter second number')
num2 = input()
total = num1 + num2
elif choice == 2:
print ('Enter second number')
num2 = input()
total = num1 - num2
elif choice == 3:
print ('Enter second number')
num2 = input()
total = num1 * num2
elif choice == 4:
print ('Enter second number')
num2 = input()
total = num1 / num2
print("Total")
print (total)
I`m getting a syntax error on the "if choice => 1 and choice =<4:" can some one please help. I have tried so many different things and nothing have worked.
This script should work for you :
total = 0
print ("Enter 1)Add 2)Minus 3)Multiply 4)Divide")
choice = int(input())
for _ in range(int(input("total test cases"))):
if choice >= 1 and choice <= 4:
if choice == 1:
print ("Enter first number")
num1 = int(input())
print ('Enter second number')
num2 = int(input())
total = num1 + num2
print("Total is: ",total)
choice=int(input("enter choice again"))
elif choice == 2:
print ("Enter first number")
num1 = int(input())
print ('Enter second number')
num2 = int(input())
total = num1 - num2
print("Total is: ",total)
choice=int(input("enter choice again"))
elif choice == 3:
print ("Enter first number")
num1 = int(input())
print ('Enter second number')
num2 = int(input())
total = num1 * num2
print("Total is: ",total)
choice=int(input("enter choice again"))
elif choice == 4:
print ("Enter first number")
num1 = int(input())
print ('Enter second number')
num2 = int(input())
total = num1 / num2
print("Total is: ",total)
choice=int(input("enter choice again"))
else:
print("wrong number entered")
choice=int(input("enter again"))
Note:If you find this answer helpful you can mark this answer correct
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 5 years ago.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Improve this question
while True:
print ("Options")
print ("Write 'Quit' if you want to exit")
print ("Write '+'if you want to make an addition")
print ("Write '-' if you want to make a sottration")
print ("Write '*' if you want to make a moltiplication")
print ("Write '/' if you wantto make a division")
user_input == input(":")
if user_input == ("+")
num1 = float(input("Enter a number...")
num2 = float(input("Enter the second number...")
result = str(num1+num2)
print("The result is"+ result)
elif user_input == ("-")
num1 = float(input("Enter a number...")
num2 = float(input("Enter the second number...")
result = str(num1-num2)
print("The result is"+ result)
elif user_input == ("*")
num1 = float(input("Enter a number...")
num2 = float(input("Enter the second number...")
result = str(num1*num2)
print("The result is"+ result)
elif user_input == ("/")
num1 = float(input("Enter a number...")
num2 = float(input("Enter the second number...")
print ("The result is"+ result)
This is the code I have created in python 2.7, but it does not work. I think there's an indentation error. Can you help me?
Fix your indentation and add a colon after each if-statement as the following and change user_input == input(':') to user_input = input(':'):
while True:
print ("Options")
print ("Write 'Quit' if you want to exit")
print ("Write '+'if you want to make an addition")
print ("Write '-' if you want to make a sottration")
print ("Write '*' if you want to make a moltiplication")
print ("Write '/' if you wantto make a division")
user_input = input(":") # fix this line
if user_input == ("+"):
num1 = float(input("Enter a number..."))
num2 = float(input("Enter the second number..."))
result = str(num1+num2)
print("The result is"+ result)
elif user_input == ("-"):
num1 = float(input("Enter a number..."))
num2 = float(input("Enter the second number..."))
result = str(num1-num2)
print("The result is"+ result)
elif user_input == ("*"):
num1 = float(input("Enter a number..."))
num2 = float(input("Enter the second number..."))
result = str(num1*num2)
print("The result is"+ result)
elif user_input == ("/"):
num1 = float(input("Enter a number..."))
num2 = float(input("Enter the second number..."))
result = str(num1/num2)
print ("The result is"+ result)
EDIT:
Below is a better version of your code that fixes few errors, like reading string input, avoid dividing by zero exception and removing float() type casting because in python 2.7 input() already does that for you.
while True:
print("Options")
print("Write 'Quit' if you want to exit")
print("Write '+'if you want to make an addition")
print("Write '-' if you want to make a sottration")
print("Write '*' if you want to make a moltiplication")
print("Write '/' if you wantto make a division")
user_input = raw_input(":")
if user_input == '+':
num1 = input("Enter a number...")
num2 = input("Enter the second number...")
print('The result is {}'.format(num1+num2))
elif user_input == '-':
num1 = input("Enter a number...")
num2 = input("Enter the second number...")
print('The result is {}'.format(num1-num2))
elif user_input == '*':
num1 = input("Enter a number...")
num2 = input("Enter the second number...")
print('The result is {}'.format(num1*num2))
elif user_input == '/':
num1 = input("Enter a number...")
num2 = input("Enter the second number...")
if num2 == 0:
print("Can't divide by zero.")
else:
print("The result is {}".format(num1/num2))
Also as suggested by other users here is an improved version:
while True:
print("Options")
print("Write 'Quit' if you want to exit")
print("Write '+'if you want to make an addition")
print("Write '-' if you want to make a sottration")
print("Write '*' if you want to make a moltiplication")
print("Write '/' if you wantto make a division")
user_input = raw_input(":")
num1 = input("Enter a number...")
num2 = input("Enter the second number...")
if user_input == "+":
result = str(num1+num2)
elif user_input == "-":
result = str(num1-num2)
elif user_input == "*":
result = str(num1*num2)
elif user_input == "/":
if num2 == 0:
result = "Can't divide by zero"
else:
result = str(num1/num2)
print("The result is", result)
I recently started learning Python. I have never coded before, but it seemed like a challenge. The first thing I have made is this calculator. However, I can't seem to get it to work.
while True:
print("Typ 'plus' to add two numbers")
print("Typ 'min' to subtract two numbers")
print("Typ 'multiplication' multiply two numbers")
print("Typ 'division' to divide two numbers")
print("Typ 'end' to abort the program")
user_input = input(": ")
if user_input == "end"
break
elif user_input == "plus":
num1 = float(input("Give a number: "))
num2 = float(input("Give another number: "))
result = str(num1 + num2)
print("The anwser is: " + str(result))
elif user_input == "min":
num1 = float(input("Give a number: "))
num2 = float(input("Give another number: "))
result = str(num1 - num2)
print("The anwser is: " + str(result))
elif user_input == "maal":
num1 = float(input("Give a number:"))
num2 = float(input("Give another number: "))
result = str(num1 * num2)
print("The anwser is: " + str(result))
elif user_input == "deel":
num1 = float(input("Give a number: "))
num2 = float(input("Give another number: "))
result = str(num1 + num2)
print("The anwser is: " + str(result))
else:
print ("I don't understand!")
I know it will probably something stupid, I am still very much learning. Just trying to pickup a new skill instead of bothering my friends who do know how to code.
You missed a colon after an this if statement
if user_input == "end"
break
Should Be:
if user_input == "end":
break
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