Functions [Live Lecture]
1
Today’s Agenda
2
Today’s Agenda
3
Announcements
4
Today’s Agenda
5
Functions: header and body
def name_of_function(parameters):
statement 1
statement 2
...
return some_value
6
HEADER�Specifies the name of the function and the data that it needs. Also called the SIGNATURE
BODY�One or more indented statements that the function will execute when called
def name_of_function(parameters):
statement(s)
return some_value
7
Keyword def marks the start of function header
A function name to uniquely identify it (snake case)
parameters (the way we pass data to a function)
colon (:) marks end of function header
function body has 1 or more statements, which have same indentation level (usually 4 spaces)
An optional return statement to return a value from the function
Today’s Agenda
8
Activity 1: Area of a Square
Write a function called get_area_sq that calculates the area of a square. Your function will take 1 argument, the length of one of the sides (float), and return the area of the square.
Reminder: to do this, you’ll have to first create a brand new Python file in Idle first, then save it (e.g. practice.py)...and then create your function.
When you’re done, invoke your function as follows:
area_1 = get_area_sq(5.5)�area_2 = get_area_sq(8)�print(area_1, area_2)
9
Activity 2: Area of a Rectangle
Now, write a function that returns the area of a rectangle. Give it a name that’s mnemonic. Consider:
When you’re done, invoke (call) your function with some different data to prove that it works.
10
Activity 3: Surface Area of a Cube
Now, write a function that returns the surface area of a cube, based on the length of a single side of the cube. Give it a name that’s mnemonic. Consider:
If you can (optional), try and see if you can make use of the get_area_sq function that you just made.
When you’re done, invoke (call) your function with some different data to prove that it works.
11
Activity 4: Surface area of a rectangular box
Finally, write a function to calculate the surface area of any box, given that you know its length, width, and height.
If you can (optional), try and see if you can make use of the get_area_rect (or whatever you called it) function that you just made.
Questions to ask yourself:
12
Practice: Activity 8 & 9
# Consider the following code:
print('*' * 12)
print('Hello Varun!')
print('*' * 12)
print('\n')
# Write a function that prints a message for any name
# with enough stars to exactly match the length of the message.
# Hint: Use the len() function.
13
Today’s Agenda
14
Find the Mistake
def area_of_square(length:int):
return length * length
def surface_area_of_cube(area:int):
area * 6
print(
'Surface area of a cube where side=10 feet is:',
surface_area_of_cube(area_of_square(10)),
'feet'
)
15