I am trying to write a program which implements a simple calculator using python. I am having trouble figuring out the simplest way of doing this (I'm a super beginner). I'm almost there but the calculator isn't running the operations. Any help would be much appreciated!!
The basic idea is that the user is prompted to enter the first number. If this number = 0 an error message is displayed and they are asked to retry. Then the operations are displayed (1-add, 2-subtract..so on). If a number is entered other 1, 2, 3 or 4, an error message is displayed. They are then prompted for the second number. Again if this is 0 an error message is displayed.
#Prompt user to enter first number
while True:
n1 = int(input('enter first number\n'))
if n1>0:
break
else:
print('Please input a number above 1')
def add():
n1 + n2
def sub():
n1-n2
def mult():
n1*n2
def div():
n1/n2
#Prompt user to enter operator
while True:
operation = int(input('What would you like to do? 1:Addition, 2:Subtraction, 3:Multiplication, 4:Division\n'))
if operation == 1:
break
elif operation == 2:
break
elif operation == 3:
break
elif operation == 4:
break
else:
print('That was not an option...')
#Prompt user to enter second number
#If operation is addition
if operation == 1:
while True:
n2 = int(input('enter second number\n'))
if n2>0:
add()
break
else:
print('That was not an option...')
#If operation is subtraction
if operation == 2:
while True:
n2 = int(input('enter second number\n'))
if n2>0:
break
else:
print('That was not an option...')
sub()
#If operation is multiplication
if operation == 3:
while True:
n2 = int(input('enter second number\n'))
if n2>0:
break
else:
print('That was not an option...')
mult()
#If operation is division
if operation == 4:
while True:
n2 = int(input('enter second number\n'))
if n2>0:
break
else:
print('That was not an option...')
div()
return
statement in your nearest Python tutorial, and see how that would apply to your functions such asadd()
. And then, use the returned value in your calling code. – Greg Hewgill 2 days ago