?print-pdf
' Created for
def task_1():
pass
def task_2():
pass
...
def task_n():
pass
def function_name(param_list):
'''docstring'''
statements
return [expression]
pass
statement for function body:
def do_task1():
pass
def do_task2():
pass
def do_task3():
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!")
Synonyms: Function Execution; Function Invocation
function_name(opt_arg_list)
### define greet() function
def greet():
"""Just prints hello"""
print("Hello!")
### execute the greet() function:
greet()
# execute the greet() function:
greet()
# define greet() function:
def greet():
print("Hello!")
# NameError: name 'greet' is not defined
# 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)
# DESIRED OUTPUT:
# 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
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(f"{msg} {name}!")
greet("Maria")
# SyntaxError: non-default argument follows default argument
def greet(name, msg="Hi"):
print(f"{msg} {name}!")
greet("Maria")
# Hi Maria!
def greet(msg, name):
print(f"{msg} {name}!")
greet(name="Maria", msg="Hi")
Named arguments must follows the positional arguments!
def greet(msg, name):
print(f"{msg} {name}!")
greet(name="Maria", "Hi")
# SyntaxError: positional argument follows keyword argument
def foo(*args):
print(args)
foo(1)
foo(1,2)
foo(1,2,3)
#(1,)
#(1, 2)
#(1, 2, 3)
The name args
can be any valid variable name, but its a convention to use *args
to denote that it contains the packed arguments
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)
add_num()
function, which will print the sum of variable number of numerical arguments
# add_num() definition
# test your code:
add_num(1)
#should print 1
add_num(1,2)
#should print 3
add_num(1,2,3)
#should print 6
**
(double stars) in front of parameter name which will receive a variable number of keyword arguments into a dictionary.
def foo(**kwargs):
print(kwargs)
foo(a=1, b=2)
# {'a': 1, 'b': 2}
def signup(**kwargs):
for k,v in kwargs.items():
print("{} - {}".format(k,v))
signup(user="ada", age=28)
signup(user="ada", age=28, town="london")
*
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!
**
(double stars) to unpack dictionary into named arguments.
def menu_print(fruit, price):
print("{:.<20s}{:.2f}".format(fruit,price))
menu_print(**{
"price": 2.5,
"fruit": "apple"
})
# apple...............2.50
return
statementreturn
statement:
def f():
statements
return [expression]
def add(x,y):
return x+y
print(add(2,4)**2)
# 36
The return statement exit the function! Any code after return
will never be executed:
def add(x,y):
return x+y
# next line will never be executed:
print("After return")
print(add(2,4))
return
statement, then the function return value is None.
def foo():
print("foo() was executed!")
def bar():
print("bar() was executed!")
return "End"
print( foo() )
print( bar() )
# OUTPUT:
# foo() was executed!
# None
# bar() was executed!
# End
In Python each function returns a value, being it None!
def f1():
y = 2
print(f"y = {y} inside f1")
f1()
# y = 2 inside f1
print(f"y = {y} outside f1")
# NameError: name 'y' is not defined
x = 10
def foo():
print("x = {} inside foo()".format(x))
foo()
# x = 10 inside foo()
print("x = {} outside foo()".format(x))
# x = 10 outside foo()
x = 1
def foo():
x = 99
print(f"x = {x} inside foo")
foo()
# x = 99 inside foo
print(f"x = {x} outside foo")
# x = 1 outside foo
Variables with same name, defined in different scopes are considered as different variables!
def outer():
x=2
def inner():
x = 3
print(f'x = {x} in inner')
inner()
print(f'x = {x} in outer')
x = 1
outer()
print(f'x = {x} in global')
#x = 3 in inner
#x = 2 in outer
#x = 1 in global
nonlocal
statementnonlocal
statement prefix
def outer():
x=2
def inner():
nonlocal x
x = 3
print(f'x = {x} in inner')
inner()
print(f'x = {x} in outer')
x = 1
outer()
print(f'x = {x} in global')
#x = 3 in inner
#x = 3 in outer
#x = 1 in global
global
statementglobal
statement prefixglobal
statement causes the listed names to be interpreted as global names.
def outer():
x=2
def inner():
global x
x = 3
print(f'x = {x} in inner')
inner()
print(f'x = {x} in outer')
x = 1
outer()
print(f'x = {x} in global')
#x = 3 in inner
#x = 2 in outer
#x = 3 in global
Although scopes are determined statically, they are used dynamically. I.e. a name is resolved searching in:
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