Boston Python Workshop 3/Friday/Tutorial: Difference between revisions

imported>Jesstess
No edit summary
imported>Jesstess
Line 613:
* They let us re-use code without having to type it out each time.
* They take input and possibly produce output. You can assign a variable to this output.
* You call a function by using its name followed by the input in parenthesis. For example:
 
For example:
 
<pre>
Line 626 ⟶ 628:
<b>Step 1: write a function signature</b>
 
A <b>function signature</b> tells you how the function will be called. It is the keyword <code>def</code>, a space, the name of your function, an open parenthesis, the comma-separated <b>parameters</b> for your function, a close paranthesis, and a colon. Here's what a function signature looks like for a function that takes no arguments:
 
<pre>
Line 644 ⟶ 646:
</pre>
 
Parameters should have names that usefully describe what they are used for in the function.
 
<b>Step 2: do useful work inside the function</b>
 
Underneath the function signature you do your useful work. Everything inside the function is indented, just like with if/else blocks, so Python knows that it is a part of the function.
 
<pre>
def add(x, y):
result = x + y
</pre>
 
<b>Step 3: return something</b>
 
If you want to be able to assign a variable to the output of a function, the function has to <b>return something</b> using the <code>return</code> keyword.
 
<pre>
def add(x, y):
result = x + y
return result
</pre>
 
or, even shorter:
 
<pre>
def add(x, y):
return x + y
</pre>
 
Once you define this function, you can use it:
 
<pre>
result = add(1234, 5678)
print result
</pre>
 
Functions don't have to return anything, if you don't want them to.
 
==End of Part 2==
Anonymous user