YCL Session 4 You put the fun in functions! Functions A function is - - PowerPoint PPT Presentation
YCL Session 4 You put the fun in functions! Functions A function is - - PowerPoint PPT Presentation
YCL Session 4 You put the fun in functions! Functions A function is a block of code that we can call with just one line. Functions give us the ability to write: Clear, easy-to-read code. The ability to reuse that code. Function
Functions
A function is a block of code that we can call with just one line. Functions give us the ability to write:
- Clear, easy-to-read code.
- The ability to reuse that code.
Function Anatomy
To create our own drawing functions we need three things, the latter two which which we learned in our last session:
- 1. How to define a function
- 2. How to use variables
- 3. How to create simple mathematical expressions
Step 1: Defining
- 5. A colon
- 6. Include 4 spaces or a tab
- 7. Then the meat of your
functions!
- 1. Comment: what does this
function do?
- 2. Use def
- 3. Then name the function
- 4. Parentheses
Example
def draw_grass(): """ This function draws the grass. """ arcade.draw_lrtb_rectangle_filled(0, 800, 200, 0, arcade.color.BITTER_LIME)
Step 2: Calling
Our computer needs to know when it should use the function we’ve just defined. To do so, just use the name of the function: draw_grass()
grass.py
1.
Create a new directory Session 4 in PyCharm
2.
Create a new file under Session 4
3.
Call it grass.py
4.
See the Code Snippet called grass.pdf
5.
Copy and paste
6.
Run!
tree.py
- 1. Create a new file under Session 4
- 2. Call it tree.py
- 3. See Code Snippet called grass.pdf
- 4. Copy and paste
- 5. Run!
Step 3: Using Expressions
forest.py
- 1. Create a new file under Session 4
- 2. Call it forest.py
- 3. See Code Snippet called grass.pdf
- 4. Copy and paste
- 5. Run!
Cylinder Volume
Function that returns the volume of a cylinder def volume_cylinder(radius, height): pi = 3.141592653589 volume = pi * radius ** 2 * height return volume Because of the return, this function could be used later on as part of an equation to calculate the volume of a six-pack like this: six_pack_volume = volume_cylinder(2.5, 5) * 6
Capturing Values
Functions can take in AND return values, as in the cylinder example BUT be careful: seeing it in the code and seeing the
- utput is not the same!
We need to “capture” the returned value in a new variable, and then print that variable outside of the function in order to see it.
Variable Scope
# Define a simple function that sets x equal to 22 def f(): x = 22 # Calling the function works f() # This fails because x only exists in f() print(x)
functions.py
1.
Create a new file under Session 4
2.
Call it functions.py
3.
See Code Snippets for reference, and Activity for Instructions
4.