在理解函数的途中,是回到基础数学。
考虑数学表达式:
f(x) = x + 2
在这种情况下,将f(x)
添加2到的x
值。
因此f(0) = 0 + 2
给出了2. 类似地对于其他值x
。
when x = 3....f(3) = 5
when x = 5....f(5) = 7
因此,对于x
的输入值,这将产生一个输出,其是表达x + 2
的评估。
在Python中,这种表达会是这样的:
def f(x): # here x is the input value
output = x + 2 #calculates the expression using x
return(x+2) #and we return the value
假设我们想找到x = 3
值。这将是:f(3)
f(3)
现在会给你5如上。
我们可以在另外一个变量保存这个值,
y =f(3)
这里y
节省当你通过3到它在我们的函数的返回值。因此Ÿ将5
在你的榜样,
def secret_formula(started): #here we have **started** instead of x
jelly_beans = started * 500 #bunch of calculations
jars = jelly_beans/1000
crates = jars/100
return jelly_beans, jars, crates #returns the calculated value
下面说,
start_point = 10000
beans, jars, crates = secret_formula(start_point) #what will the output be , if I give 1000 to secret_formula .. ie... secret_formula(1000)
现在secret_formula
函数返回三个输出
return jelly_beans, jars, crates
我们来分配这些输出beans, jars, crates
按照相应的顺序。
现在beans
将有jelly_beans
具有的价值,等等...
所以发生了什么事jelly_beans
?粗略地说,函数中使用的变量只能在其中使用。将它们视为一旦使用后丢弃的中间值。阅读范围和范围规则。
该函数将返回一些我们现在存储在其他变量中的值。
当您必须重复执行某些操作时,函数可能非常有用。而不是一次又一次重写相同的代码,您可以调用该函数。
考虑这一点,随机场景:
def printNow():
print("Hiwatsup, blah blah blah ")
#some insane calculations
print("Hiwatsup, blah blah blah ")
#more random things.
现在,每当你想要做所有这些事情,你只需要把printNow()
。 你不必重新输入所有内容!
很好,你正在学习Python,但这是一个非真正的问题......如果你对特定代码示例的困难有疑问,那会更好。 – jumbopap
你不明白哪部分功能? –
所以你的问题基本上是:功能如何工作?似乎有点宽泛。请把它缩小到你不了解的部分功能。 –