Created for
def function_name(opt_param_list):
'''docstring'''
statements
return [expression]
pass
statement for function body:
def my_fun():
pass
You can use the pass
statement anywhere in your code, where you need a "do nothing" block!
def greet():
"""Just prints hello"""
print("Hello!")
Note, this code will not print anything if you try to run it as is.
This is just the function's definition. In order to execute the statements in it, the function should be called!
Synonyms: Function Execution; Function Invocation
The statements in the body of a function will be executed only when the function is called:
function_name(opt_arg_list)
# execute the greet() function:
greet()
Note, the braces after the function name are required!
A function must be defined before you call it, or a NameError will be raised!
# execute the greet() function:
greet()
# define greet() function:
def greet():
print("Hello!")
print(5/2)
# NameError: name 'greet' is not defined
function call - the right way:
# define greet() function:
def greet():
print("Hello!")
# execute the greet() function:
greet()
# Hello!
def add():
print(2+3)
add()
add()
add()
# 5
# 5
# 5
# call add with different arguments:
add(20, 22)
add(123, 321)
add(16, 10)
# 42
# 444
# 26
def sub(x,y):
""" subtracts y from x and prints the result """
print(x - y)
sub(99)
# TypeError: sub() missing 1 required positional argument: 'y'
sub(99, 3, 3)
# TypeError: sub() takes 2 positional arguments but 3 were given
But you can use default parameters values.
def greet(name="Nobody"):
""" greets a user """
print("Hello", name)
greet("Maria")
greet()
# Hello Maria
# Hello Nobody
Default parameters must follow the non-default parameters!
def greet(msg="Hi", name):
print("{} {}!".format(msg, name))
greet("Maria")
# SyntaxError: non-default argument follows default argument
def greet(name, msg="Hi"):
print("{} {}!".format(msg, name))
greet("Maria")
# Hi Maria!
def greet(msg, name):
print("{} {}!".format(msg, name))
greet(name="Maria", msg="Hi")
Named arguments must follows the positional arguments!
def greet(msg, name):
print("{} {}!".format(msg, name))
greet(name="Maria", "Hi")
# SyntaxError: positional argument follows keyword argument
def add(*args):
add = 0
for item in args:
add += item
print(add)
add(1, 2)
add(1, 2, 3)
add(1, 2, 3, 4)
The name args
can be any valid variable name, but its a convention to name the unpacked arguments with args
Variable arguments must follow the positional arguments:
def add(p1, *args):
print(p1, end=", ")
print(args)
add(1, 2)
add(1, 2, 3)
add(1, 2, 3, 4)
# 1, (2,)
# 1, (2, 3)
# 1, (2, 3, 4)
**
(double stars) to unpack dictionary into keyword parameters.
def menu_print(fruit, price):
print("{:.<20s}{:.2f}".format(fruit,price))
menu_print(**{
"price": 2.5,
"fruit": "apple"
})
# apple...............2.50
*
operator
def my_func(p1,p2,p3):
print(p1, p2, p3)
args = [1,2,3]
my_func(*args)
# 1 2 3
Note, that if you miss the star in my_func(*[1,2,3])
, Python will assign the whole list [1,2,3]
to p1
, and the rest of parameters will receive no value. That will throw an error!
return
statementreturn
statement:
def f():
statements
return [expression]
def add(x,y):
return x+y
print(add(2,4)**2)
# 36
The return statement exits a function!
def add(x,y):
return x+y
# next line will never be executed:
print("After return")
print(add(2,4))
return
statement, or if there is no expression after return
keyword, then the function return value is None
def foo():
print("foo() was executed!")
def bar():
print("bar() was executed!")
return
print( foo() )
print( bar() )
# OUTPUT:
# foo() was executed!
# None
# bar() was executed!
# None
def f1():
y = 2
print("y = {} inside f1(): ".format(y))
f1()
# y = 2 inside f1()
print("y = {} outside f1(): ".format(y))
# NameError: name 'y' is not defined
x = 10
def f1():
print("x = {} inside f1()".format(x))
f1()
# x = 10 inside f1()
print("x = {} outside f1()".format(x))
# x = 10 outside f1()
x = 10
def f1():
x = 99
print("x = {} inside f1()".format(x))
f1()
# x = 99 inside f1()
print("x = {} outside f1()".format(x))
# x = 10 outside f1()
Variables with same name, defined in different scopes are considered as different variables!
def get_user_data():
"""retrieves user data from the command line
Returns:
[dictionary] of the form:
{
"name" : "user_name",
"height": "user heigth in meters",
"weight": "user weight in kilograms"
}
"""
pass
def calc_BMI(w,h):
"""calculates the BMI
Arguments:
w {[float]} -- [weight]
h {[float]} -- [height]
Returns:
[float] -- [calculated BMI = w / (h*h)]
"""
pass
def calc_BMI_category(bmi):
"""Calculates the BMI category
Arguments:
bmi {[float]} -- [the bmi number index]
Returns:
[string] -- [bmi category]
"""
pass
def print_results(bmi_category):
"""[Prints the BMI category to the user ]
Arguments:
bmi_category {[string]} -- []
"""
pass
def cm_to_meters(cm):
"""converts centimetres to meters
Arguments:
cm {[int]}
Returns:
[float]
"""
pass
user_data = get_user_data()
bmi = calc_BMI(user_data["weight"],user_data["height"] )
bmi_category = calc_BMI_category(bmi)
print_results(bmi_category)
get_user_data()
defined in Task1, adding a check for valid user data:These slides are based on
customised version of
framework