我在从函数中使用另一个函数的输出时遇到问题。 我不知道python中函数的语法。当我定义它时,如何在函数中使用另一个函数的输出。 def hero_attribute(hero_selection()):#此语法未被接受
#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()
答案 0 :(得分:1)
函数是一段接收参数的代码,并为这些参数指定一个名称。例如:
def square(x):
return x * x
此函数计算数字的平方;函数体中的这个未知数字将被称为x
。
一旦你有了一个功能,你可以调用它,传递你想要的值作为参数...例如
print( square(12) )
将打印144
,因为它会调用square
传递x=12
和12*12
144
的函数。
你当然可以传递一个函数调用另一个函数的结果,例如
def three_times(x):
return 3 * x
print( square( three_times(5) ) )
将显示225,因为函数three_times
将被传递5并且它将返回3*5
,函数square
将被传递15
并将返回15*15
}。
在功能定义(def
部分)中,参数总是只有名称。您要传递给该功能的内容将写在致电网站。
答案 1 :(得分:0)
你想要的是能够传递函数作为参数。然而,这已经从设计中融入到python中:你只需在传递任何其他参数时传递它。
示例:
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的定义是第一个参数是一个函数。只有在您真正阅读apply
的定义时才知道。在那里你看到f
被视为一个函数,而不是被视为“数字”的x。