How to print variable from subroutine - python

In my code below, I don't know why when the output total_cost is zero, and why the subroutine doesn't change that variable. Also are the parameters of my subroutine wrong, like should I add them outside the subroutine and then use those defined variables or something?
total_cost = 0
from datetime import date
def valid_integer():
not_valid = True
while not_valid:
try:
number = int(input())
not_valid = False
except ValueError:
print("You must enter a whole number")
return number
print("Welcome to Copington Adventure them park!")
print(
"\n""These are our ticket prices:"
"\n""Adult ticket over 16's £20 "
"\n""Child ticket under 16's £12 "
"\n""Senior ticket over 60's £11" )
print("How many adult tickets do you want?")
adult = int(input())
print("How many child tickets do you want?")
child = int(input())
print("How many Senior tickets do you want?")
senior = int(input())
print("Your total ticket price is:")
print(total_cost)
def entrance(child_total, adult_total, senior_total):
total_child = child * 12
total_senior = senior * 11
total_adult = adult * 20
total_cost = total_child + total_senior + total_adult
return total_cost
print(total_cost)

return exits the function, so any code after a return will not execute. Swap the order of these two lines:
return total_cost
print(total_cost)
The required reading on this is "scope". Code in a function has access to the variables in its own scope, and it has access to its parent scope, which is the file it was defined in. After a function call completes, the scope, and all variables created in it that aren't returned or stashed in a higher scope, tend to be destroyed.
Returned variables are passed back to the caller's scope. So the lifecycle is something like this:
def myfunction(a, b):
a = a * 2
print(a) #this will evaluate later when we call the function
b = a + b
return b
c = myfunction(1, 2) # jumps to the first line of the function with a=1 and b=2
# the function evaluates, which prints "2" and returns 4.
# The label "c" is then created in the outer scope, and 4 is assigned to it. So now c = 4
print(a) # this is an error, a is not part of this outer scope
print(b) # this is an error, b is not part of this outer scope
print(c) # outputs 4
print(myfunction(1, 2)) # what do you think this outputs?

Related

Is there a way to set a variable in a function without resetting the variable every time the function runs?

So what I mean by this is if you have this code for example:
def test():
money = 0
x = input('')
if x == "givemoney":
money = money + 100
print(money)
test()
else:
print("something")
test()
It'll reset money to 0 every time the function goes which makes sense but how could I stop that?
You should use a loop. Here money is defined and initialized in a scope local to the function when the function is called; this is why it reset for every call to test().
def test():
money = 0
x = input('')
while x != 'stop':
if x == "givemoney":
money = money + 100
print(money)
x = input('')
else:
print("something")
test()
In the first version you can make money an optional parameter to the function. When you call it from the top-level you allow it to default. When you make the recursive call, you pass the current value in place of the default.
def test(money = 0):
x = input('')
if x == "givemoney":
money = money + 100
print(money)
test(money)
else:
print("something")
test()

Desk Price Calculation in Python

I have a little exercise I need to do in Python that's called "Desk Price Calculation". There need to be 4 functions which are used in the program.
My main problem is using the output of a function in another function.
def get_drawers():
drawers = int(input('How many goddamn drawers would you like? '))
return drawers
def get_wood_type():
print('The types of wood available are Pine, Mahogany or Oak. For any other wood, type Other')
wood = str(input('What type of wood would you like? '))
return wood
def calculate_price(wood_type, drawers):
wood_type = get_wood_type()
drawers = get_drawers()
wood_price = 0
drawer_price = 0
#wood price
if wood_type == "Pine":
wood_price = 100
elif wood_type == "Oak":
wood_price = 140
elif wood_type == "Mahogany":
wood_price = 180
else:
wood_price = 180
#price of drawers
drawer_price = drawers * 30
return drawer_price + wood_price
def display_price(price, wood, drawer_count):
price = calculate_price()
wood = get_wood_type()
drawer_count = get_drawers()
print("The amount of drawers you requested were: ", drawer_count, ". Their total was ", drawer_count * 30, ".")
print("The type of would you requested was ", get_wood_type(), ". The total for that was ", drawer_count * 30 - calculate_price(), ".")
print("Your total is: ", price)
if __name__ == '__main__':
display_price()
I guess you get an error like this (that should have been added to your question by the way) :
Traceback (most recent call last):
File "test.py", line 42, in <module>
display_price()
TypeError: display_price() missing 3 required positional arguments: 'price', 'wood', and 'drawer_count'
You defined your display_price() function like this :
def display_price(price, wood, drawer_count):
So it expects 3 arguments when you call it, but you call it without any.
You have to either :
redefine your function without argument (that would be the most logical solution since price, wood and drawer_count are defined in its scope.
pass these arguments to the call of this function, but that would be useless for the reason I mentionned in 1. Unless you remove these arguments definition.
PS: You'll have the same problem with calculate_price() since it expects two arguments, but you pass none to it.
About function's arguments :
When you define a function, you also define the arguments it expects when you call it.
For instance, if you define :
def f(foo):
# Do some stuff
a correct f call would be f(some_val) and not f()
Plus it would be useless to define f like this :
def f(foo):
foo = someval
# Do some other stuff
since foo is direcly redefined in the function's scope without even using the initial value.
This will help you to discover functions basics :
http://www.tutorialspoint.com/python/python_functions.htm
It would appear that you wanted to pass in some parameters to your method.
If that is the case, you need to move the "calculate" and "get" functions.
And, no need to re-prompt for input - you already have parameters
def calculate_price(wood_type, drawers):
# wood_type = get_wood_type()
# drawers = get_drawers()
wood_price = 0
drawer_price = 0
# ... other calulations
return drawer_price + wood_price
def display_price(wood, drawer_count):
price = calculate_price(wood, drawer_count)
### Either do this here, or pass in via the main method below
# wood = get_wood_type()
# drawer_count = get_drawers()
print("The amount of drawers you requested were: ", drawer_count, ". Their total was ", drawer_count * 30, ".")
print("The type of would you requested was ", wood, ". The total for that was ", drawer_count * 30 - price, ".")
print("Your total is: ", price)
if __name__ == '__main__':
wood = get_wood_type()
drawer_count = get_drawers()
display_price(wood, drawer_count)

nested function in python (taking the output from another function)

I have problem with getting output from another function to use in a function.
I don't know the syntax of function in python. How do i take a output of another function to use in a function when i define it.
def hero_attribute(hero_selection()): #This syntax isn't accepted
#This program will calculate the damge of hero with stats
global hero_str_result
global hero_agi_result
global hero_int_result
def hero_selection():
print """1. Life Stealer (strength hero)\n
2. Phantom lancer (agility hero)\n
3. Phantom Assassin (agility hero)\n
4. Wrait King (strength hero) \n
"""
print "Please enter hero selection: "
hero_num = int(raw_input("> "))
return hero_num
def hero_attribute(hero_selection()): #This syntax isn't accepted
if hero_num == 1: # Life stealer
hero_str = 25
hero_agi = 18
hero_int = 15
#Hero growth stats
str_growth = 2.4
agi_growth = 1.9
int_growth = 1.75
elif hero_num == 2: # Phantom lancer
hero_str =
hero_agi = ?
hero_int = ?
#Hero growth stats
str_growth = 2.4
agi_growth = 1.9
int_growth = 1.75
elif hero_num == 3: # Phantom Assassin
hero_str = ?
hero_agi = ?
hero_int = ?
#Hero growth stats
else: #Wraith King
hero_str = ?
hero_agi = ?
hero_int = ?
#hero growth stats
str_growth = ?
agi_growth = ?
int_growth = ?
return (hero_str,hero_agi,hero_int,str_growth,agi_growth,int_growth)
def hero_type(hero_num):
if hero_num == 1:
hero_type = "str"
elif hero_num == 2
hero_type = "agi"
elif hero_num == 3
hero_type = "agi"
else:
hero_type = "str"
#the function will ask user what to do with the hero
def hero_build():
print "What do you want to do with the hero?"
print """1. Build hero with stat
2. Build hero with item (not yet)
3. Build hero with level
"""
user_choice = int(raw_input("> "))
if user_choice == 1:
print "You want to build hero with stats!"
print "Please enter number of stats that you want to add: "
hero_stats = int(raw_input=("> "))
hero_str, hero_agi, hero_int,str_growth,agi_growth,int_growth = hero_attribute() #This function will take the result of hero_str, hero_agi,hero_int
hero_str_result = hero_str + str_growth * hero_stats
hero_agi_result = hero_agi + agi_growth * hero_stats
hero_int_result = hero_int + int_growth * hero_stats
return hero_str_result, hero_agi_result, hero_int_result
print "This is the result of your build: ", hero_build()
A function is a piece of code that receive arguments, and to those arguments you assign a name. For example:
def square(x):
return x * x
this function computes the square of a number; this unknown number in the body of the function will be called x.
Once you have a function you can call it, passing the values you want as arguments... for example
print( square(12) )
will print 144 because it will call the function square passing x=12 and 12*12 is 144.
You can of course pass a function the result of calling another function, e.g.
def three_times(x):
return 3 * x
print( square( three_times(5) ) )
will display 225 because the function three_times will be passed 5 and it will return 3*5, the function square will be passed 15 and will return 15*15.
In the function definition (the def part) you will always just have names for the parameters. What you want to pass to the function will be written at the call site.
What you want is to be able to pass a function as argument. This, however, is already incorporated into python from design: you simply pass it as you pass any other argument.
Example:
def apply(f,x):
return f(x)
def sq(x):
return x*x
def cb(x):
return x*x*x
apply(sq,2)
4
apply(cb,2)
8
Apply is defined with its first argument being a function. You know that only when you actually read the definition of apply. There you see that f is treated as a function, as opposed to x which is treated "as a number".

Python 3 craps simulation

I'm not sure how I could incorporate my roll() function into the playRound(). The playRound is supposed to simulate the actual round of craps. I have to have the roll() function as is along with all of the other code. The only segment I can edit is the playRound() function.
from random import (random, randint)
def roll():
return randint( 1, 6 ), randint( 1, 6 )
def playRound():
def main():
print("Craps simulation")
while True:
response = input("Enter an integer value > 0 ")
if response == "":
print("Thank you for your business!")
break
try:
num_trials = int(response)
if num_trials < 1:
raise ValueError("Input must be >= 1 ")
roundsPlayed = 0
wins = 0
while roundsPlayed < num_trials:
roundsPlayed += 1
if playRound():
wins += 1
print( "Probability of winning is {0:>0.2%}".format( wins/num_trials ) )
except ValueError as err:
print( err )
except TypeError as err:
print( err )
main()
You are allowed to call any function as long as it is in scope. In Python, every function defined on the outermost scope layer is callable from anywhere within the script (or module namespace, if you're using it as such). This is referred to as the global scope.
When you have a function that returns multiple values, Python lets you catch them very easily with different variables by using commas to separate them.
Here's a small example of calling roll within playRound and storing the return values in two variables:
def playRound():
roll1, roll2 = roll()

Python: Using defs in a program about ordering stuff

This program is about ordering stuff from a "mail order" house thing.
They sell five products. P1 = 2.98, P2 = 4.5, P3 = 9.98, P4 = 4.49, P5 = 6.87
So this is my code so far.
#Imports: None
#Defs:
def userInput1():
x = int(input("Product Number?"))
return x
def userInput2():
q = int(input("Quantity?"))
return q
def calculations(x,q):
p1 = 2.98
p2 = 4.5
p3 = 9.98
p4 = 4.49
p5 = 6.87
subtotal = q * x
return subtotal
def final(subtotal):
print ("Total:", subtotal)
def loop():
cont = input("Do you want to continue? (yes/no)")
if cont == 'yes':
main()
return
else:
final()
def main():
x = userInput1()
subtotal = calculations(x,q)
final(subtotal)
#Driver:
main()
I have to use a sentinel controlled loop.
Here's my traceback.
Traceback (most recent call last):
File "C:\Documents and Settings\user1\My Documents\Downloads\az_mailorder3.py", line 49, in <module>
main()
File "C:\Documents and Settings\user1\My Documents\Downloads\az_mailorder3.py", line 46, in main
subtotal = calculations(x,q)
NameError: name 'q' is not defined
Here's how it should work.
Product number?: 1
Quantity?: 2
Continue?(yes/no): yes
Product number?: 2
Quantity?: 5
Continue?(yes/no): yes
Product number?: 3
Quantity?: 3
Continue?(yes/no): yes
Product number?: 4
Quantity?: 1
Continue?(yes/no): no
Total: $62.89
There's probably deeper problems.
Assuming you are a newbie to programming (I can feel that from your code) and also this problem seems a school homework which is quite easy and also you don't want to try hard debugging it (You need to debug a lot to be a good programmer)
Here I am presenting your code to you with proper comments why your code is going wrong.
Start reading from the main function (not from the first line)
def userInput1():
x = int(input("Product Number?"))
return x
def userInput2():
q = int(input("Quantity?"))
return q
def calculations(x,q):
p1 = 2.98
p2 = 4.5
p3 = 9.98
p4 = 4.49
p5 = 6.87
subtotal = q * x
#here you are multiplying the item number by quantity
#not the price by quantity (use proper if else to check price for item number
# return to main function again for more comments
return subtotal
def final(subtotal):
print ("Total:", subtotal)
#nothing wrong here but since we have declared subtotal as global (remember that?)
#so no need to pass subtotal by argument.
def loop():
cont = input("Do you want to continue? (yes/no)")
if cont == 'yes':
main()
return
else:
final()
#you are calling final() but you declared with argument (are you mad?)
#now check final function
def main():
x = userInput1()
#Where you are taking input from user for quantity??
#first take quantity as input q = userInput2()
subtotal = calculations(x,q)
#now every time you call main function your subtotal will be revised
#remember teacher talking about global and local variables?
#subtotal needs to be global (declare it somewhere outside the functions
#now even if subtotal is global you need to increment it (not reassign)
# use subtotal += calculations(x,q)
#now check your calculations function
final(subtotal)
#you are calling final subtotal but where the hell you calling your loop?
#call it before calling final and now check your loop function
main()
hopefully by now you are able to write correct code
but even if you are not able to write correct code by now here is something for your help. But try to write code by yourself first. Happy Debugging :)

Categories