How to move out of function - python

i am novice to python and i have stuck at one point, though its a simple program
I have used 'Return False' to move out of the function but i want to move out of my function completely. How it can be done.
Also if i want to run this script from python shell, how it can be done.
def menu():
print "calculator using functions"
print "Choose your option:"
print " "
print "1) Addition"
print "2) Subtraction"
print "3) Multiplication"
print "4) Division"
print "5) Quit calculator.py"
print " "
return input ("Choose your option: ")
def add(a,b):
print a, "+", b, "=", a + b
print " Do you want to continue: "
decide=raw_input("yes or no: ")
if decide== "no" or decide== 'n':
print(" You have exited ")
return False
elif decide=='yes' or decide== 'y':
menu()
else:
print "wrong choice!!!"
return False
# 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
loop = 1
choice = 0
while loop == 1:
choice = menu()
if choice == 1:
add(input("Add first No: "),input("Add second No: "))
elif choice == 2:
sub(input("Add first No: "),input("Add second No: "))
elif choice == 3:
mul(input("Add first No: "),input("Add second No: "))
elif choice == 4:
div(input("Add first No: "),input("Add second No: "))
elif choice == 5:
loop = 0
print "End of program!"

You want to use exit. It exits from the program.
import sys
def spam():
.
.
.
if some_condition:
sys.exit(0) # exits from the program
.
.
.

You don't have to explicitly return anything to exit a function. When the interpreter reaches the end of the function block, the function exits.

On the command line type:
python myprogram.py
to run the program from prompt, if you want to use a specific python shell (other than bash or cmd) then you need to look to the documentation of that specific shell (e.g http://www.dreampie.org/).
To exit from a function use:
return
To exit from a program use:
import sys
sys.exit(0)

Related

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")

Making selections linked to definitions in 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)

My first program

I've been doing a lot lessons on Code Academy, but I get frustrated since some of the compilers reject answers that return the same results. So, I decided to breakaway for a bit and create my own program with the tools that I have learned which is a calculator. It doesn't run correctly. When it is at the menu the if/elif/else statements do not work. The program seems to ignore the input . So, here is my first program code...
import math
user_choice=(">>")
def add():
print "What two numbers would you like to add?"
a= int(raw_input(user_choice))
b= int(raw_input(user_choice))
c= a + b
print c
def sub():
print "What two numbers would you like to subtract?"
a=int(raw_input(user_choice))
b=int(raw_input(user_choice))
c=a-b
print c
def mult():
print "What two numbers would you like to multiply?"
a=int(raw_input(user_choice))
b=int(raw_input(user_choice))
c= a*b
print c
def div():
print "What two numbers would you like to divide?"
a=int(raw_input(user_choice))
b=int(raw_input(user_choice))
c=a/b
print c
def exp():
print "What number would you like to power?"
a=int(raw_input(user_choice))
print "By what number would you like it to be powered to?"
b=int(raw_input(user_choice))
c= math.pow(a,b)
print c
def square():
print "What number would you like to square root?"
a=int(raw_input(user_choice))
b=math.sqrt(a)
print b
print "+---------------------------+"
print "| Welcome to my basic |"
print "| calculator! |"
print "| |"
print "|What would you like to do? |"
print "| |"
print "|1: Addition |"
print "|2: Subtraction |"
print "|3: Multiplication |"
print "|4: Division |"
print "|5: Exponents |"
print "|6: Square Root |"
print "|7: Quit |"
print "| |"
print "+---------------------------+"
if int(raw_input(user_choice)) == "1":
add()
elif int(raw_input(user_choice)) == "2":
sub()
elif int(raw_input(user_choice)) == "3":
mult()
elif int(raw_input(user_choice)) == "4":
div()
elif int(raw_input(user_choice)) == "5":
exp()
elif int(raw_input(user_choice)) == "6":
square()
elif int(raw_input(user_choice)) == "7":
exit()
else:
print "Sorry, I didn't understand your entry.Try entering a value 1-7"
there is no "if error" code yet, but I am just adamant about getting it to work. All of the functions work. Just can't get the options to work.
int(rawinput()) will return an integer, which will not be == to a string like "1". Remove the int() from them and it should work.
Change
if int(raw_input(user_choice)) == "1":
To
if int(raw_input(user_choice)) == 1:
Number should not be quoted, only literal string should.
A suggestion, you can get the input just once, and then do the if/elif/else conditional test, for example:
option = int(raw_input(user_choice))
print "You choose %d" % option
if option == 1:
add()
elif option == 2:
sub()
......
Besides the things others have pointed out, I will leave here how I personally would implement it. This surely isn't the best way, but I hope it might give you some idea (which you either will adopt or reject) and some points where you can investigate further in order to broaden your python skills:
class Operation:
def __init__(self, f, argc):
#f is the function to use, argc the number of arguments it takes
self.f = f
self.argc = argc
def __call__(self):
#read in the args
args = [int(input('>> ')) for _ in range (self.argc)]
#print out the result of the function passed in the ctor
print(self.f(*args))
#your operations keyed to the options of your menu
operations = {'1': Operation(lambda a, b: a + b, 2),
'2': Operation(lambda a, b: a - b, 2),
'3': Operation(lambda a, b: a * b, 2),
'4': Operation(lambda a, b: a / b, 2),
'5': Operation(lambda a, b: a ** b, 2),
'6': Operation(lambda a: a ** .5, 1)}
while True:
print('''
1: Addition
2: Subtraction
3: Multiplication
4: Division
5: Exponentiation
6: Square root
7: Quit''')
choice = input('Your choice: ') #raw_input for py2
if choice == '7': break
try: operations[choice]()
#KeyError means choice is not in the dict
except KeyError: print('Unkown option')
#Something else went wrong, division by zero, etc
except Exception as e: print('Something went horribly wrong: {}'.format(e))

How to go back to first if statement if no choices are valid

How can I have Python move to the top of an if statement if no condition is satisfied correctly.
I have a basic if/else statement like this:
print "pick a number, 1 or 2"
a = int(raw_input("> ")
if a == 1:
print "this"
if a == 2:
print "that"
else:
print "you have made an invalid choice, try again."
What I want is to prompt the user to make another choice for this if statement without them having to restart the entire program, but am very new to Python and am having trouble finding the answer online anywhere.
A fairly common way to do this is to use a while True loop that will run indefinitely, with break statements to exit the loop when the input is valid:
print "pick a number, 1 or 2"
while True:
a = int(raw_input("> ")
if a == 1:
print "this"
break
if a == 2:
print "that"
break
print "you have made an invalid choice, try again."
There is also a nice way here to restrict the number of retries, for example:
print "pick a number, 1 or 2"
for retry in range(5):
a = int(raw_input("> ")
if a == 1:
print "this"
break
if a == 2:
print "that"
break
print "you have made an invalid choice, try again."
else:
print "you keep making invalid choices, exiting."
sys.exit(1)
You can use a recursive function
def chk_number(retry)
if retry==1
print "you have made an invalid choice, try again."
a=int(raw_input("> "))
if a == 1:
return "this"
if a == 2:
return "that"
else:
return chk_number(1)
print "Pick a number, 1 or 2"
print chk_number(0)
Use a while loop.
print "pick a number, 1 or 2"
a = None
while a not in (1, 2):
a = int(raw_input("> "))
if a == 1:
print "this"
if a == 2:
print "that"
else:
print "you have made an invalid choice, try again."

Categories