Home >Backend Development >Python Tutorial >Python的return如何理解?
比如learn python the hard way 里的
<span class="k">def</span> <span class="nf">add</span><span class="p">(</span><span class="n">a</span><span class="p">,</span> <span class="n">b</span><span class="p">):</span> <span class="k">print</span> <span class="s">"ADDING </span><span class="si">%d</span><span class="s"> + </span><span class="si">%d</span><span class="s">"</span> <span class="o">%</span> <span class="p">(</span><span class="n">a</span><span class="p">,</span> <span class="n">b</span><span class="p">)</span> <span class="k">return</span> <span class="n">a</span> <span class="o">+</span> <span class="n">b</span>
<code class="language-python"><span class="k">def</span> <span class="nf">worker</span><span class="p">(</span><span class="n">a</span><span class="p">,</span> <span class="n">b</span><span class="p">,</span> <span class="n">c</span><span class="p">):</span>
<span class="n">x</span> <span class="o">=</span> <span class="n">a</span> <span class="o">+</span> <span class="n">b</span>
<span class="n">y</span> <span class="o">=</span> <span class="n">x</span> <span class="o">*</span> <span class="n">c</span>
</code>
return 语句就是将结果返回到调用的地方,并把程序控制权一起返回。<code class="language-text">num = add(a, b)
</code>
好像被邀请了. 先占个坑. 开始写答案,一会写好了粘过来.
卧槽得到了1个赞!来修正下!def autoparts():
parts_dict={}
list_of_parts = open('list_of_parts.txt', 'r')
for line in list_of_parts:
k, v = line.split()
parts_dict[k] = v
return parts_dict
为什么return?如果你不return,那么你建立的这个字典就挂了,在function运行完后其结果不可再被访问,因为你仅仅是把结果print到输出设备上。如果你return了这个结果,那么结果会被保留,那么你还可以在这个结果的基础上做些其它事情,如:my_auto_parts=autoparts()
print my_auto_parts['engine']
当我们再调用autoparts这个function时,它将return的值给我们,我们可以把这个return的值储存在my_auto_parts这个变量里,我们可以在autoparts这个function运行完后,依然通过my_auto_parts这个变量来获取字典里的内容,最后我们可以输出字典里关键词“engine”的目标。
首先,你是在定义一个函数,使用它的时候要调用它