ycl session 4 you put the fun in functions functions
play

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


  1. YCL Session 4 You put the ’fun’ in functions!

  2. 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.

  3. 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

  4. 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

  5. Example def draw_grass(): """ This function draws the grass. """ arcade.draw_lrtb_rectangle_filled(0, 800, 200, 0, arcade.color.BITTER_LIME)

  6. 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()

  7. 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.

  8. 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!

  9. Step 3: Using Expressions

  10. 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!

  11. 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

  12. 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.

  13. 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)

  14. 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