Making selections linked to definitions in python - python

So how this was thought to work was: Start script, make a selectable menu so the user can select what to do (add, divide, multiply and so forth). But I can't seem to figure out how to do it.
Something like this:
Press 1 for add
Press 2 for multiply
and so forth. I have just made the add definition as of now, but I plan on using the same template when doing multiply and divide etc.
# Calculations
def add(a, b):
print "Write the numbers to add"
adda = int(raw_input("First number: "))
addb = int(raw_input("Second number: "))
print "Adding %d and %d together" % (a, b)
print "%d + %d="
return a + b
# Choose what to do
print "Write what you want do do: add, subtract, multiply or divide"
EDITED TO:
# Calculations
def math(command):
print "Write the numbers to %s" % command
a = int(raw_input("First number: "))
b = int(raw_input("Second number: "))
if command == 'add':
return a + b
elif command == 'subtract':
return a - b
elif command == 'multiply':
return a * b
elif command == 'divide':
return a / b
else:
return 'not a valid command'
# Choose what to do
print "Write what you want to do.. add, subtract, multiply or divide"
command = raw_input("Do you want to add, multiply, divide or subtract: ")
Problem here is that it won't print out the value for return a + b for example, I don't have any link to the def math(), so I don't think it will run.. any way to solve this?

You should use raw_input to find out what the user wants to do, similar to how you get the numbers in the add() function.
# Choose what to do
choice = raw_input("Write what you want do do: add, subtract, multiply or divide")
if choice == 'add':
add()
However because in add() you ask for the numbers the user wants to add, you do not want to call add() with parameters, so change
def add(a, b):
to
def add():
Later, when you have the other functions implemented as well you can do something like
# Choose what to do
choice = raw_input("Write what you want do do: add, subtract, multiply or divide")
if choice == 'add':
add()
elif choice == 'subtract'
subtract()
elif choice == 'multiply'
multiply()
elif choice == 'divide'
divide()
else:
print 'not a valid choice'
i plan on using the same template when doing multiply and divide etc.
In that case you could do something like this
def dostuff(command):
print "Write the numbers to %s" (command)
a = int(raw_input("First number: "))
b = int(raw_input("Second number: "))
if command == 'add':
return a + b
elif command == 'subtract':
return a - b
elif command == 'multiply':
return a * b
elif command == 'divide':
return a / b
else:
return 'not a valid command'
# Choose what to do
command = raw_input("Write what you want do do: add, subtract, multiply or divide")
print dostuff(command)

Related

How do I reset my calculator, when I enter "$" to input , instead of a number , python

I need to reset this calculator when user enter "$" instead first or second input number or user enter "$" end of the input number (ex: 5$,20$).
the (a,b) is input number1 and number2. it was assigned as global varibles.
select_op(choice) is function, running the operation that user need. input_function() is function for input two numbers.
# Functions for arithmetic operations.
def add(a,b):
return (a+b) # 'a' and 'b' will add.
def subtract(a,b):
return (a-b) # 'b' substract from 'a'.
def multiply(a,b):
return (a*b) #'a' multiply by 'b'.
def divide(a,b):
if b == 0 : .
return None
else:
return (a/b) # 'a' divided by 'b'.
def power(a,b):
return (a**b) # 'a' power of 'b'.
def remainder(a,b):
if b == 0:
return None
else:
return (a%b) # reminder of 'a' divided by 'b'.
#this function for out put of operation
def select_op(choice): #this function will select operation
if choice == "+":
input_function()
print(a,' + ',b,' = ',add(a,b))
elif choice == "-":
input_function()
print(a,' - ',b,' = ',subtract(a,b))
elif choice == "*":
input_function()
print(a,' * ',b,' = ',multiply(a,b))
elif choice == "/":
input_function()
if b==0:
print("float division by zero")
print(a,' / ',b,' = ',divide(a,b))
elif choice == "^":
input_function()
print(a,' ^ ',b,' = ',power(a,b))
elif choice == "%":
input_function()
if b==0:
print("float division by zero")
print(a,' % ',b,' = ',remainder(a,b))
elif choice == "#": #if choice is '#' program will terminate.
return -1
elif choice == "$": #if choice is '$' program reset.
return None
else:
print("Unrecognized operation")
#this function for input two operands.
def input_function():
number1=float(input("Enter first number: "))
number2=float(input("Enter second number: "))
global a,b
a=number1
b=number2
return a,b
#loop repeat until user need to terminate.
while True:
print("Select operation.")
print("1.Add : + ")
print("2.Subtract : - ")
print("3.Multiply : * ")
print("4.Divide : / ")
print("5.Power : ^ ")
print("6.Remainder: % ")
print("7.Terminate: # ")
print("8.Reset : $ ")
# take input from the user
choice = input("Enter choice(+,-,*,/,^,%,#,$): ")
print(choice)
if(select_op(choice) == -1):
#program ends here
print("Done. Terminating")
exit()
Be sure to check whether the string returned from input() ends with a "$" before converting it to a float.
To reset when a user types something that ends with "$", you could throw an exception to break out of your calculator logic and start over. We'll surround the stuff inside your while loop with a try/catch, so that the exception doesn't stop your program, but merely starts a new iteration in the while loop.
# I omitted all your other functions at the start of the file
# but of course those should be included as well
class ResetException(Exception):
pass
#this function for input two operands.
def input_function():
s = input("Enter first number: ")
if s.endswith("$"):
raise ResetException()
number1=float(s)
s = input("Enter second number: ")
if s.endswith("$"):
raise ResetException()
number2=float(s)
global a,b
a=number1
b=number2
return a,b
#loop repeat until user need to terminate.
while True:
print("Select operation.")
print("1.Add : + ")
print("2.Subtract : - ")
print("3.Multiply : * ")
print("4.Divide : / ")
print("5.Power : ^ ")
print("6.Remainder: % ")
print("7.Terminate: # ")
print("8.Reset : $ ")
# take input from the user
try:
choice = input("Enter choice(+,-,*,/,^,%,#,$): ")
print(choice)
if(select_op(choice) == -1):
#program ends here
print("Done. Terminating")
exit()
except ResetException:
pass

can you help me with this? im trying to crete a simple calculator using python

ive been trying to run this code but the fuctions i have created are not being called
def add(*args,**kwargs):
sum=0
for m in args:
sum=sum+m
for n in kwargs.values():
sum=sum+n
return sum
def subtract(*args,**kwargs):
sum=0
for m in args:
sum=m-sum
for n in kwargs.values():
sum=n-sum
return sum
def multiply(*args,**kwargs):
sum=1
for m in args:
sum=m*sum
for n in kwargs.values():
sum=n*sum
return sum
def divide(*args,**kwargs):
sum=1
for m in args:
sum=m/sum
for n in kwargs.values():
sum=n/sum
return sum
def square(*args,**kwargs):
sum=1
for m in args:
sum=sum*m**2
for n in kwargs.values():
sum=sum*n**2
return sum
def Menu():
print """
What operation do you want to perform?
1. Addition
2. Subtraction
3. Multiply
4. Divide
5. Square
6. Exit
"""
choice = input("Enter choice:")
tup1= float(input("Enter numbers: "))
if choice == ("1,add, Add"):
print add()
elif choice == ("2,subtract, Subtract"):
print subtract()
elif choice == ("3,multiply, Multiply"):
print divide()
elif choice == ("4,divide, Divide"):
print multiply()
elif choice == ("5,square, Square"):
print multiply()
elif choice == ("6,exit, Exit"):
exit()
else:
Menu()
Menu()
Choice will never equal all of ("6,exit, Exit"). What you want is
if choice in ("6","exit", "Exit"):
The code below converts the choice string to lowercase, then checks if it matches anything in the list.
if choice.lower() in ['1','add']:
print add(1,2,3)
change the lines where you are checking for choices:
if choice == ("1,add, Add"):
to:
if choice in ["1", "add", "Add"]:
At the moment you are checking for an exact string

don't matter what the input is it won't get to the "else if" statement [duplicate]

This question already has answers here:
How can I read inputs as numbers?
(10 answers)
Closed 4 years ago.
my output is the menu() function prints only all over again and again, don't matter what the input is it won't get to the "else if" statement #Python...........................................................................
def menu():
#print what options you have
print ("Welcome to calculator.py")
print ("your options are:")
print (" ")
print ("1) Addition")
print ("2) Subtraction")
print ("3) Multiplication")
print ("4) Division")
print ("5) exposion")
print ("6) Quit calculator.py")
print (" ")
return input ("Choose your option: ")
# this adds two numbers given
def add(a,b):
print (a, "+", b, "=", a + b)
# this subtracts two numbers given
def sub(a,b):
print (b, "-", a, "=", b - a)
# this multiplies two numbers given
def mul(a,b):
print (a, "*", b, "=", a * b)
# this divides two numbers given
def div(a,b):
print (a, "/", b, "=", a / b)
# HERE IS MY CODE
def dinami(base, exponent):
if y == 1:
print (base, "*" ,power,"(",base,",", exponent," - 1) = ",base)
if y != 1:
print (base, "*" ,power,"(",base,",", exponent," - 1) = ",base * power(base, exponent - 1))
# NOW THE PROGRAM REALLY STARTS, AS CODE IS RUN
loop = 1
while loop == 1:
choice = menu()
if choice == 1:
add(input("Add this: "),input("to this: "))
print ("hi")
elif choice == 2:
sub(input("Subtract this: "),input("from this: "))
elif choice == 3:
mul(input("Multiply this: "),input("by this: "))
elif choice == 4:
div(input("Divide this: "),input("by this: "))
elif choice == 5:
dinami(input("expone this: "),input("to this: "))
elif choice == 6:
loop = 0
print ("Thankyou for using calculator.py!")
input() returns a string, so if you're comparing int with string i.e '1' == 1, which always returns False
https://docs.python.org/3/library/functions.html#input

what's this indentationError?

print("Welcome to calculator.py")
print ("your options are :")
print ("")
print ("1) Addition")
print ("2)Subtraction")
print ("3) Multiplication")
print ("4)Division")
print ("Choose your option")
#this adds 2 numbers given
def add (a,b):
print(a, "+" ,b, "=" ,a+b)
#this subtracts 2 numbers given
def sub (a,b):
print(a, "-" ,b, "=" ,b-a)
#this multiplies 2 numbers given
def mul(a,b):
print(a, "*" ,b, "=" ,a*b)
#this divides 2 numbers given
def div(a,b):
def div(a, "/" ,b, "=" ,a/b)
#NOW THE PROGRAM REALLY STARTS ,AS CODE IS RUN
loop = 1
choice = 0
while loop == 1:
choice = menu()
if choice == 1:
add (input("Add this: "),input ("to this: "))
elif choice == 2:
sub(input("Subtract this: "),input ("from this: "))
elif choice == 3:
mul (input("Multiply this: "),input ("by this: "))
elif choice == 4:
div(input("Divide this: "),input ("by this: "))
elif choice ==5:
loop = 0
print ("Thank you for using calculator.py")
this is my code and the error is:
print(a, "+" ,b, "=" ,a+b)
^
IndentationError: expected an indented block
Process finished with exit code 1
and many others can anyone help me find all the errors???
can anyone help me???
In python, there are identation rules to know how the program should execute commands. This is the way python recognize when a function, a conditional statement or for, while statements start and end. In your case, for example, the elif statement should be at the same "level" as your initial if statement start:
print("Welcome to calculator.py")
print ("your options are :")
print ("")
print ("1) Addition")
print ("2)Subtraction")
print ("3) Multiplication")
print ("4)Division")
print ("Choose your option")
#this adds 2 numbers given
def add (a,b):
print(a, "+" ,b, "=" ,a+b)
#this subtracts 2 numbers given
def sub (a,b):
print(a, "-" ,b, "=" ,b-a)
#this multiplies 2 numbers given
def mul(a,b):
print(a, "*" ,b, "=" ,a*b)
#this divides 2 numbers given
def div(a,b):
def div(a, "/" ,b, "=" ,a/b)
#NOW THE PROGRAM REALLY STARTS ,AS CODE IS RUN
loop = 1
choice = 0
while loop == 1:
choice = menu()
if choice == 1:
add (input("Add this: "),input ("to this: "))
elif choice == 2:
sub(input("Subtract this: "),input ("from this: "))
elif choice == 3:
mul (input("Multiply this: "),input ("by this: "))
elif choice == 4:
div(input("Divide this: "),input ("by this: "))
elif choice ==5:
loop = 0
In python blocks are defined by indentation. After defining function you should have a indentation(tab).
Pretty much all of the indentation is wrong, not just that one place:
print("Welcome to calculator.py")
print("your options are :")
print("")
print("1) Addition")
print("2)Subtraction")
print("3) Multiplication")
print("4)Division")
print("Choose your option")
#this adds 2 numbers given
def add(a,b):
print(a, "+", b, "=" , a+b)
#this subtracts 2 numbers given
def sub(a,b):
print(a, "-", b, "=" , b-a)
#this multiplies 2 numbers given
def mul(a,b):
print(a, "*", b, "=" , a*b)
#this divides 2 numbers given
def div(a,b):
print(a, "/", b, "=", a/b)
#NOW THE PROGRAM REALLY STARTS, AS CODE IS RUN
loop = 1
choice = 0
while loop == 1:
choice = menu()
if choice == 1:
add(input("Add this: "), input("to this: "))
elif choice == 2:
sub(input("Subtract this: "), input("from this: "))
elif choice == 3:
mul(input("Multiply this: "), input("by this: "))
elif choice == 4:
div(input("Divide this: "), input("by this: "))
elif choice ==5:
loop = 0
print ("Thank you for using calculator.py")

python calculator program with expected indented block error

I have created a python calculator, I need to get it to restart, I have added the loop:
#This line defines the end of the program so it restarts.
def sys():
#These lines will define each operation.
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
#This asks the user what operation they would like to use
print("Please select operation ")
print("1. Add")
print("2. Subtract")
print("3. Multiply")
print("4. Divide")
#This tells the user to enter the number of the operation they would like
operation = input("Enter operation(1/2/3/4):")
#This asks the user to input the two numbers they would like the calculator to calculate
num1 = int(input("Please enter first number: "))
num2 = int(input("Please enter second number: "))
#This is the part of the program that will calculate the calculations
if operation == '1':
print(num1, "+", num2, "=", add(num1,num2))
elif operation == '2':
print(num1,"-",num2,"=", subtract(num1,num2))
elif operation == '3':
print(num1,"*",num2,"=", subtract(num1,num2))
elif operation == '4':
print(num1,"/",num2,"=", subtract(num1,num2))
else:
print("Invalid input")
inp = input("Enter clear to play again or exit to exit")
if inp == "clear":
sys()
else:
print("thanks for playing")
sys.exit()
It keeps saying expected an indented block and shows, that it wants the indent in front of:
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
but when I add them in, it keeps saying, that the operation is not defined. I also feel like the loop will not work either.
It looks like you are trying to recursively re-run the code, in which case you probably want e.g.
import sys # so you can use sys.exit()
def add(x, y): # no need for these function definitions to be in the loop
...
...
def main(): # conventional name - sys shadows the module you just imported
print("Please select operation ")
print("1. Add")
...
inp = input("Enter clear to play again or exit to exit")
if inp == "clear":
main()
else:
print("Thanks for playing")
sys.exit() # or just 'return'
if __name__ == "__main__": # if run directly, rather than imported
main()
You can define functions within other functions (although there's no need here), but remember you need another level of indentation:
def outer(n):
def inner(x):
return x ** 2
return 2 * inner(n)
Note that using recursion means you will eventually hit the system recursion depth limit; iteration is probably wiser:
def main():
while True:
...
inp = input("Enter clear to play again or exit to exit")
if inp != "clear":
print("Thanks for playing")
break
You may be interested in this solution to your problem. It makes use of the operator module, which provides named functions for all the standard Python operators. It also uses a list to translate the operation number to a function and a symbol for printing.
from operator import add, sub, mul, div
operations = [
(add, '+'),
(sub, '-'),
(mul, 'x'),
(div, '/'),
]
while True:
print('1. Add')
print('2. Subtract')
print('3. Multiply')
print('4. Divide')
op = int(raw_input('Enter operation (1/2/3/4): '))
if 0 < op <= len(operations):
func, sym = operations[op-1]
num1 = float(raw_input('Please enter first number: '))
num2 = float(raw_input('Please enter second number: '))
print('{} {} {} = {}'.format(num1, sym, num2, func(num1, num2)))
else:
print('Invalid operation')
continue
while True:
inp = raw_input('Enter clear to play again or exit to exit: ')
if inp == 'exit':
print('Thanks for playing')
exit()
elif inp == 'clear':
break
output
1. Add
2. Subtract
3. Multiply
4. Divide
Enter operation (1/2/3/4): 3
Please enter first number: 8
Please enter second number: 9
8.0 x 9.0 = 72.0
Enter clear to play again or exit to exit: exit
Thanks for playing
If you have an empty function, put in the phrase pass as in:
def some_func():
pass
And that error will no longer occur.

Categories