# Example 1: implementing a max function from scratch
my_list = [1, 7, 3, 6, 9]
maximum = my_list[0]
for element in my_list:
if element > maximum:
maximum = element
# this is the output of our codes above
print(maximum)
9
max(1, 2, 4, 3)
# Now we use the built-in max(...) function instead
# the built-in function max(...) encapsulates all the different steps above into one single command
print(max(my_list))
9
# Define your custom max function!
def beta_alpha(my_list):
maximum = my_list[0]
for element in my_list:
if element > maximum:
maximum = element
return maximum # output of the function
beta_alpha([1, 2, 4, 3])
max([1, 2, 4, 3])
# Example 2: define a function for calculating the area of a circle
def circle_area(radius):
pi = 3.14159
area = pi * radius **2
return area
# we can call the function like so
circle_area(10) # this is a function call
3.14159 * 10 * 10
# which is local variable?
pi
NameError: name 'pi' is not defined
def dummy_function():
"""
This function has no output
"""
# do something
pi = 3.14
dummy_function()
# function with no outputs
result = print("I am Kevin")
I am Kevin
result
# function with no return statement
# the function definition includes many important parts
def circle_area(radius): # function header, starts with the 'def' keyword
# The body of a function is indented
pi = 3.14159
# if there is no return statement, the function would return None
return pi * radius * radius # the return statement sends back an output value to the function call
def cylinder_volume(radius, height):
"""
This function computes the volume of a cylinder
Args:
- radius
- height
"""
pi = 3.14159
return pi * radius * radius * height
# adding docstring
cylinder_volume(10, 1)
def do_something(arg1, arg2):
summation = arg1 + arg2
return summation
do_something(11, 2)
def do_something(arg1, arg2):
addition = arg1 + arg2
multiplication = arg1 * arg2
return (addition, multiplication)
do_something(11, 2)
# you can unpack the tuple
summation, product = do_something(1, 2)
type(do_something(1, 2))
product
# Print vs. Return in Functions
# Here are two valid functions. One returns a value and one simply prints a value, without returning anything.
def print1(text1, text2):
"""
This function only prints a text to the console
Args:
- text1
- text2
"""
print(text1 + " and " + text2) # this function returns no output
def print2(text1, text2):
"""
This function returns something
"""
return text1 + " and " + text2
dummy1 = print1("Anna", "Bernard") # which goes to argument 1 and argument 2?
dummy2 = print2("Anna", "Bernard")
Anna and Bernard
print(dummy1)
None
dummy2
print("print1 returns the value: {}".format(dummy1))
print("print2 returns the value: {}".format(dummy2))
print1 returns the value: None
print2 returns the value: Anna and Bernard
# assigning it to a value suppress the output (only in Notebook)
print1("Anna", "Bernard")
Anna and Bernard
# Example 3: using default arguments in a function
def circle_area(radius = 1): # we can specify a default value for the argument
"""
This function calculates the area of a circle given radius.
If user does not specify a value for the radius, the default value is used
"""
pi = 3.14159
return pi * radius * radius
print(circle_area(1))
3.14159
print(circle_area()) # this is the same as calling the function with radius = 1
3.14159
# passing the radius argument by position
print(circle_area(10)) # override the default value of 1
314.159
# passing the radius argument by name
print(circle_area(radius = 10))
314.159
def cylinder_volume(radius, height):
pi = 3.14159
return pi * radius * radius * height
cylinder_volume(1, 2)
cylinder_volume(height = 1, radius = 2)
%run -i students.py
Unsupported output type: clearOutput
The chosen one is: Gavin Chandra
# Exercise 1: write a function to compute population density
# <your code here> (~ 2 lines)
def population_density(population, area):
return population/area
# test cases for your function
medan_population = population_density(2068000, 261)
expected_result1 = 2068000/261.
print("expected result: {}, actual result: {}".format(expected_result1, medan_population))
expected result: 7923.371647509579, actual result: 7923.371647509579
# integer division
8 // 7
# modulo operator
8 % 7
# Exercise 2: write a function that takes an integer number of days
# and return a string with the number of weeks and days that is.
def timedelta(days):
number_of_weeks = days // 7
number_of_days = days % 7
return "{} week(s) and {} day(s).".format(number_of_weeks, number_of_days)
# test your function
print(timedelta(8)) # should return 1 week and 1 day
print(timedelta(10)) # should return 1 week and 3 days
1 week(s) and 1 day(s).
1 week(s) and 3 day(s).
# give an example of an assignment statement
size = 7
# give an example of a for loop
for _ in range(10):
print("repeat")
repeat
repeat
repeat
repeat
repeat
repeat
repeat
repeat
repeat
repeat
# give an example of a method call
# a method is a function that belongs to an object
"Hello World".lower()
# give an example of a while loop
numbers = list(range(10))
while len(numbers) > 0:
numbers.pop()
print(numbers)
[]
# give an example of a built-in function
# what is the name of the function?
# what is the argument to the function?
range(10) # range is the name, 10 is the argument
# give an example of a function that is called with no argument
list()
def my_function():
some_variable = 1 # this is a local variable
print(some_variable)
my_function()
1
# this will give an error
print(some_variable)
NameError: name 'some_variable' is not defined
def happy_function():
some_variable = "Hello"
return some_variable
my_function()
1
some_variable = 0 # some_variable is a global variable here
def my_function():
# accessing a global variable from inside a function is OK
print(some_variable)
my_function()
0
print(some_variable)
0
# Case study: what happens if we try to modify a global variable inside a function?
balance = 0 # this is a global variable
def top_up():
balance += 20
top_up()
UnboundLocalError: local variable 'balance' referenced before assignment
# Case study: what happens if we try to modify a global variable inside a function?
balance = 0 # this is a global variable
def top_up():
balance += 20
def print_balance():
print(balance)
print_balance()
0
# Case study: what happens if we try to modify a global variable inside a function?
# If you want to change the global variable balance, pass it as an argument
balance = 0
def top_up(balance):
# the correct way to write the top_up function is by passing the balance as an argument
balance += 20
return balance
balance = top_up(balance)
print(balance)
20
# Quiz 2.1: what is printed by the following
str1 = 'Hello World'
def print_fn():
str1 = 'Hello There'
print(str1)
print_fn()
# Question: what is printed?
# A. "Hello World"
# B. "Hello There"
# C. Nothing is printed
Hello There
# Quiz 2.2: what is printed by the following
str1 = 'Hello World'
def print_fn():
#str1 = 'Hello There'
print(str1)
print_fn()
# Question: what is printed?
# A. Hello World
# B. Hello There
# C. An error occurs
Hello World