I am working on a calculator in python as one of my assignments for class (basic operations, addition, subtraction, multiplication, and division) I have a print menu from which the user can choose what operation they want to use… and then enter their integers and an print statement of what the answer is. My problem is that I need to repeat my initial input of what operation the user would like to execute. New to programming so any help is greatly appreciated.
Here is my code:
print ("1 = addition")
print ("2 = subtraction")
print ("3 = multiplication")
print ("4 = division")
print ("5 = Exit program\n")
x = int (input ("What operation would you like to perform?: ")) #prompts user for operation
if (x == 1): #if operation chose is addition then this line will exacute
int1 = input ("Enter first integer: ")
int1 = int (int1)
int2 = input ("Enter second integer: ")
int2 = int (int2)
sum = int1 + int2
print ("Sum is:", sum)
elif (x == 2): #if operation chose is subtraction then this line will exacute
int1 = input ("Enter first integer: ")
int1 = int (int1)
int2 = input ("Enter second integer: ")
int2 = int (int2)
dif = int1 - int2
print ("Difference is:", dif)
elif (x == 3): #if operation chose is multiplication then this line will exacute
int1 = input ("Enter first integer: ")
int1 = int (int1)
int2 = input ("Enter second integer: ")
int2 = int (int2)
mult = int1 * int2
print ("Multiplication is:", mult)
elif (x == 4): #if operation chose is division then this line will exacute
int1 = input ("Enter first integer: ")
int1 = int (int1)
int2 = input ("Enter second integer: ")
int2 = int (int2)
div = int1 / int2
print ("Division is: %.2f" % div)
elif (x == 5):
print ("goodbye")
quit()
You can split that code into a function:
Edit: It seems you have stated that it’s python 2.7, so I cleaned the code for you.
You do not need int(int1) and int(int2) because input() does not make the input a string. i.e:
Whereas raw_input() would do: