1 of 12

Functions

2 of 12

first, gradescope practice

use this code: Y7W45Y

Joining a Course - Gradescope Help Center

Submit “Lab 1”

3 of 12

revisiting types and python nonsense

1 and True

0 and False

4 of 12

Key concepts

keywords: def, return, global, input

  • call-site / invocation
  • difference between return and print
  • scope
  • state

5 of 12

Anatomy (syntax) of a function

def _____ ( ____ ):

______

...

return ____

6 of 12

Anatomy (syntax) of a function

def _____ ( ____ ):

______

...

return ____

def functionName ( parameters ):

body

...

return returnValue

7 of 12

Anatomy (syntax) of a function

def _____ ( ____ ):

______

...

return ____

def functionName ( parameters ):

body

...

return returnValue

def add ( num_one, num_two ):

result = num_one + num_two

return result

print( add(4, 3) )

8 of 12

Semantics of a function

when a function is called, the body of the function is executed

replace the parameters of the function take on the values provided at the call site (arguments). The order of the arguments tells us which parameters to use.

after executing the function, the call-site of a function is replaced with return value

9 of 12

scope

how many functions can see a variable

def foo():� x = 2�print(x) <-- this will not work

x = 2�def foo():� print(x) <-- this is fine, but actually not great

10 of 12

scope best practice

try to never use global scope

try to keep functions “state-less”/ “pure”

be aware of the global keyword, but if you are using, see if you can do restructure your code instead

11 of 12

An example

12 of 12

Homework 1 - due Monday at midnight

https://replit.com/@MarkSantolucito/geometry

Create modules for triangles, spheres, and cylinders and populate them with functions for calculating perimeter and area in the 2-D case (triangles - specifically, just equilateral triangles, so perimeter and area just take one argument) and volume and surface area in the 3-D cases (spheres and cylinders - cylinder will need radius and height). The function names should be exactly as bolded above. Modify the geometry.py file to include these as options for the user.

Submit your triangle.py , sphere.py , cylinder.py , and your modified main.py files to the appropriate place on Gradescope.