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".
Related
I'm trying to figure out how to direct a function to a function. What I'm trying to do is answer a prompt question y/n that would run a certain function. When I input y, it will run through both functions instead of only function 1.
Thanks!
def company_type(question, public_company, private_company):
print("Is the target company public on NYSE or NASDAQ?")
prompt = f'{question} (y/n)'
ans = input(prompt)
if ans == 'y':
return (public_company)
if ans == 'n':
print("Please enter financial infomation manually.")
return (private_company)
company_type("public_company", "private_company", 1)
# function 1
def public_company():
return (print("Success 1"))
public_company()
# function 2
def private_company():
return (print("Success 2"))
private_company()
You can absolutely return a function to be used later - this is the essence of functional programming, and the reason to have functions as first class objects in python ~ Guido Van Rossum.
The important thing is to remember that parens mean a function call, whereas no parens mean the function object.
def public_company():
print("we do what public companies do")
def private_company():
print("we do what private companies do")
def choose_company():
ans = input("Is the target company public?")
if ans == 'y':
return public_company # no parens
else:
return private_company # no parens
if __name__ == '__main__':
# assign the returned function to selected_company
selected_company = choose_company()
# calling selected_company() will call the selected function
selected_company() # use parens, this is a function call!
You don't really want to return a function. You just want one function to call another function. That's done like this:
# function 1
def public_company():
return print("Success 1")
# function 2
def private_company():
return print("Success 2")
def company_type(question, public_company, private_company):
print("Is the target company public on NYSE or NASDAQ?")
prompt = f'{question} (y/n)'
ans = input(prompt)
if ans == 'y':
return public_company()
else:
print("Please enter financial information manually.")
return private_company()
company_type("some question", public_company, private_company)
And please note that return statements in Python do not use an extra set of parentheses. That's a C idiom.
Errors:-
function is not a keyword.
We can call a function by:- <function_name>().
# function 1
def public_company():
print("Success")
# function 2
def private_company():
print("Success")
def company_type():
print("Is the target company public on NYSE or NASDAQ?")
prompt = 'Is your company a public company? (y/n)'
ans = input(prompt)
if ans == 'y':
public_company()
if ans == 'n':
print("Please enter financial information manually.")
private_company()
company_type()
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?
I want to develop a script that convert Measuring units based in user input . and after the script run to last code it give me this error (Unbound Local Error: local variable 'answer' referenced before assignment)
python v is 3.7.3.
as I mentioned above (and I am new to python ) the script is convert Measuring units based on user input but it give me this error . so
I’ve tried different way by moveing print function from the bottom my function it worked with the error but not with actual script because it give my "none"
python
def convart(MU , oMU , NUM):
if MU.lower == "in" and oMU.lower =="cm":
answer= float(NUM)* 2.54
print("{} {} is = {} {}".format(NUM,MU.upper,MUcm,oMU.upper))
elif MU.lower == "cm" and oMU.lower =="in":
answer= float(NUM) / 2.54
print("{} {} is = {} {}".format(NUM,MU.upper,answer,oMU.upper))
# return ("{} {} is = {} {}".format(NUM,MU.upper,answer,oMU.upper))
Fmu = input("Please Enter your Measuring unit >>")
Smu= input("Please Enter Measuring units you want to convert to >>")
number = input(" Enter the number >>")
print(convart(Fmu,Smu,number))
“I expect the output of 2 in is = 5.08 cm , but the actual output "None"
Replace all your calls to lower with lower() (and similarly replace upper with upper()), so your function would look like this:
def convart(MU , oMU , NUM):
if MU.lower() == "in" and oMU.lower() == "cm":
answer = float(NUM) * 2.54
print("{} {} is = {} {}".format(NUM, MU.upper(), MUcm, oMU.upper()))
elif MU.lower() == "cm" and oMU.lower() == "in":
answer = float(NUM) / 2.54
print("{} {} is = {} {}".format(NUM, MU.upper(), MUcm, oMU.upper()))
However, you're not returning anything from your function, i.e.: it returns None by default, so print(convart(... will print None. So your function must return the variable answer:
def convart(MU , oMU , NUM):
answer = 0 # any default value to be returned if neither tests are true
if MU.lower() == "in" and oMU.lower() == "cm":
answer = float(NUM) * 2.54
print("{} {} is = {} {}".format(NUM, MU.upper(), MUcm, oMU.upper()))
elif MU.lower() == "cm" and oMU.lower() == "in":
answer = float(NUM) / 2.54
print("{} {} is = {} {}".format(NUM, MU.upper(), MUcm, oMU.upper()))
return answer
lower and upper are methods, not keywords. So change lower & upper to lower() and upper().
"any_string".lower()/upper()
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)
While working on my program I have run into a problem where the information stored in Menu option 1 is not being transferred to Menu option 2. As you can see it is correctly stored when in menu one. When it returns to go to menu option 2 its like it never went to option 1.
update #1:
some suggestions I've had is to understand scope? from what I can tell the program is not passing the data along to its parent program even though I've typed out return in each of the definitions.
#Must be able to store at least 4 grades
#Each class can have up to 6 tests and 8 hw's
#Weighted 40%*testavg 40% hw average attendance is 20%
#User must be able to input a minimum grade warning
#after each test the your program must calculate the students average and issue warning if necessary
##Define the Modules##
import math
def menu (a): #2nd thing to happen
menuend = 'a'
while menuend not in 'e':
menuend = raw_input("Type anything other then 'e' to continue:\n")
print "What would you like to do ?"
menudo = 0
print "1 - Enter Courses\n2 - Select Course to Edit\n3 - Save File\n4 - Load File\n5 - Exit\n"
menudo = input("Enter Selection:")
if (menudo == 1):
menuchck = 0
menuchck = raw_input("\nYou have entered #1 (y/n)?:\n")
if menuchck in ["Yes","yes","y","Y"]:
x = m1()
else:
print "I'm sorry,",nam,",for the confusion, lets try again\n"
menu()
elif (menudo == 2):
menuchck1 = 0
menuchck1 = raw_input("\nYou have entered #2 (y/n)?:\n")
if menuchck1 in ["Yes","yes","y","Y"]:
x = m2()
else:
print "I'm sorry,",nam,",for the confusion, lets try again\n"
menu()
elif (menudo == 3):
print "Entered 3"
elif (menudo == 4):
print "Entered 4"
else:
print "Anything Else Entered"
def course(): #3rd thing to happen
b = {}
while True:
while True:
print "\n",name,", please enter your courses below ('e' to end):"
coursename = raw_input("Course Name:")
if (coursename == 'e'):
break
will = None
while will not in ('y','n'):
will = raw_input('Ok for this name : %s ? (y/n)' % coursename)
if will=='y':
b[coursename] = {}
print "\n",name,", current course load:\n",b
coursechck = None
while coursechck not in ('y','n'):
coursechck = raw_input("Are your courses correct (y/n)")
if coursechck =='y':
return b
else:
b = {}
print
##Menu Options##
def m1():
a = course()
return a
def m2():
print "Excellent",name,"lets see what courses your enrolled in\n"
print x
return x
###User Input Section###
name = raw_input("Enter Students Name:\n")
a = {}
menu(a)
raw_input("This is the end, my only friend the end")
In your if-elif blocks in the do==1 case, you write m1(), but for the last case, you write x=m1(). You should have the latter everywhere (by typing m1() you only run the function, but do not store the returned x anywhere).
By the way, you can avoid this if-elif confusion using if chck in ["Yes","yes","Y","y"]: