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 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 1. Comment: what does this 5. A colon function do? 6. Include 4 spaces or a tab 2. Use def 7. Then the meat of your 3. Then name the function functions! 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 Create a new directory Session 4 in PyCharm 1. Create a new file under Session 4 2. Call it grass.py 3. See the Code Snippet called grass.pdf 4. Copy and paste 5. Run! 6.
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 output 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 Create a new file under Session 4 1. Call it functions.py 2. See Code Snippets for reference, and Activity for 3. Instructions Use Session 2 drawing for inspiration! 4.
Recommend
More recommend