Ha Khanh Nguyen (hknguyen)
# define a function
def my_function(x, y, z=1.5):
if z > 1:
return z * (x + y)
else:
return z / (x + y)
# execute the function
my_function(1, 2, 3)
9
my_function(1, 2)
4.5
def
keyword to define a function.my_function()
above, x
, y
, and z
are the arguments.z=1.5
means that if no value is provided for z
, the default value of z
is 1.5.# define a function
def function_without_argument():
print('I\'m still a function!')
# execute the function
function_without_argument()
I'm still a function!
# define the function
def my_function(x, y, z=1.5):
if z > 1:
return z * (x + y)
else:
return z / (x + y)
# execute the function
my_function(1, 2, 3)
9
# execute the function
my_function(1, 2, 0.5)
0.16666666666666666
# example 1
def func():
a = 5
return a
func()
5
print(a)
--------------------------------------------------------------------------- NameError Traceback (most recent call last) <ipython-input-11-bca0e2660b9f> in <module> ----> 1 print(a) NameError: name 'a' is not defined
# example 2
a = 0
def another_func():
b = a + 1
return b
another_func()
1
a
0
def f():
a = 5
b = 6
c = 7
return a, b, c
a, b, c = f()
print(a)
print(b)
print(c)
5 6 7
def short_function(x):
return x * 2
equiv_anon = lambda x: x * 2
short_function(2)
4
equiv_anon(2)
4
Write a function named largest_mult_of_three()
that takes in 4 input: x
, y
, z
and w
(which represents a positive number). Find the largest number that is divisible by 3 among those 4 numbers and return it as the function output.
If none of the numbers are divisible by 3, return -1.
def largest_mult_of_three(x, y, z, w):
# define the function below
This lecture notes referenced materials from Chapter 3 of Wes McKinney's Python for Data Analysis 2nd Ed.