2015-12-30 70 views
0

几天前我开始学习python(2.7),使用LearnPythonTheHardWay,现在我正在学习功能,我有点失落。有人可以解释我他们是如何工作的(如果可能的话,一个例子和另一个例子更难)?如果你知道一些能够帮助我的旅程,我将不胜感激。 谢谢。 PS:我以前没有任何编程知识。我从头开始。python函数问题

例如(简单的(从书)):

def secret_formula(started): 
    jelly_beans = started * 500 
    jars = jelly_beans/1000 
    crates = jars/100 
    return jelly_beans, jars, crates 

start_point = 10000 
beans, jars, crates = secret_formula(start_point) 

print "With a starting point of: %d" % start_point 
print "We'd have %d beans, %d jars, and %d crates." % (beans, jars, crates) 

如何jelly_beans成为豆?什么是(开始)?...

+2

很好,你正在学习Python,但这是一个非真正的问题......如果你对特定代码示例的困难有疑问,那会更好。 – jumbopap

+2

你不明白哪部分功能? –

+1

所以你的问题基本上是:功能如何工作?似乎有点宽泛。请把它缩小到你不了解的部分功能。 –

回答

2

一般在编程,否则,你应该把功能看作是输入和输出。例如:

def square(num): 
    return num**2 

returns(重要的关键字)的值num**2,这是因为NUM平方**在Python幂。 但是,你可以在定义里面有东西不返回任何东西(没有实际的输出)。例如:

def square(num): 
    squared = num**2 

实际上不会返回任何东西。但是,它仍然是一个有效的功能。

如果你继续学习python,你会遇到很多函数。即使你变得更加熟练,你仍然可能会继续难以理解困难的人,所以不要太担心。如果有什么特别的东西你不明白,这将是一个很好的问题。对于更复杂的函数的例子:

def fibonnaci(n=1): 
    if n in [1,2]: 
     return 1 
    else: 
     return fibonnaci(n-1)+fibonnaci(n-2) 
+1

伟大的导师课 – Gang

2

在此行中:

beans, jars, crates = secret_formula(start_point) 

据分配secret_formula的豆返回值。

在secret_formula内部,它创建了只存在于secret_formula内部的jelly_beans变量。在运行secret_formula之后,可以将由return jelly_beans, jars, crates定义的结果分配给新变量。在这种情况下,它将这些变量分配给beans, jars, crates

因此,豆类等于jelly_beans,罐子相等,罐子和箱子等于板条箱。

+1

克莱顿,你的说明超级,我会投票给你的。 – Gang

1

在理解函数的途中,是回到基础数学。

考虑数学表达式:

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()。 你不必重新输入所有内容!