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

Content added Content deleted
imported>Jesstess
No edit summary
imported>Jesstess
Line 613: Line 613:
* They let us re-use code without having to type it out each time.
* 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.
* 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:
* You call a function by using its name followed by the input in parenthesis.

For example:


<pre>
<pre>
Line 626: Line 628:
<b>Step 1: write a function signature</b>
<b>Step 1: write a function signature</b>


A function signature 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:
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>
<pre>
Line 644: Line 646:
</pre>
</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==
==End of Part 2==