Functions
first, gradescope practice
revisiting types and python nonsense
1 and True
0 and False
Key concepts
keywords: def, return, global, input
Anatomy (syntax) of a function
def _____ ( ____ ):
______
...
return ____
Anatomy (syntax) of a function
def _____ ( ____ ):
______
...
return ____
def functionName ( parameters ):
body
...
return returnValue
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) )
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
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
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
An example
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.