Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
Imagine if you had to rewrite the "print()" function for every program
you wrote
Function Structure
def name_of_function()
def say_hi()
print('Hi!')
say_hi()
# Hi
def say_hi()
return 'Hi!'
greeting = say_hi()
print(greeting) # 'Hi!'
return
Example
Coin Flips
from random import random
def flip_coin()
r = random()
if r > 0.5:
return "Heads"
else:
return "Tails"
print(flip_coin())
Generating Evens
1
def generate_evens()
return [num for num in range(1,50) if num % 2 0]
2
def generate_evens()
result = []
for x in range(1,50)
if x % 2 0:
result.append(x)
return result
Parameter
Parameters vs Arguments
Variables that are passed to a function - think of them as placeholders that get
assigned when you call the function.
Naming Parameters
# Not great
def print_full_name(string1, string2)
return(f"Your full name is {string1} {string2}")
# Better
def print_full_name(first_name, last_name)
return(f"Your full name is {first_name} {last_name}")
Example
def yell(word)
return f"{word.upper()}!"
print(yell("hello"))
def sum_odd_numbers(numbers)
total = 0
for num in numbers:
if num % 2 != 0:
total += num
return total
2. Unnecessary else
def is_odd_number(num)
if num % 2 != 0:
return True
else:
return False
def is_odd_number(num)
if num % 2 != 0:
return True
return False
Default Parameters
def add(a,b)
return a+b
add() # 30
add(1,10) # 11
Example
def show_information(first_name="Stranger", is_instructor=False)
if first_name "Stranger" and is_instructor:
return "Welcome back instructor Colt!"
elif first_name "Stranger":
return "I really thought you were an instructor "
return f"Hello {first_name}!"
def add(a,b)
return a+b
def subtract(a,b)
return a-b
math(2,2) # 4
math(2,2, subtract) # 0
Scope
Variables created in functions are scoped in that function!
instructor = 'Colt'
def say_hello()
return f'Hello {instructor}'
def say_hello()
instructor = 'Colt'
return f'Hello {instructor}'
say_hello()
print(instructor) # NameError
Global
total = 0
def increment()
total += 1
return total
increment() # Error!
Lets us reference variables that were originally assigned on the global scope
total = 0
def increment()
global total
total += 1
return total
increment() # 1
Nonlocal
def outer()
count = 0
def inner()
nonlocal count
count += 1
return count
return inner()
You will not find yourself using the global or nonlocal keyword frequently - but
it's essential to understand for scope!
Documenting functions
Use """ """
def say_hello()
"""A simple function that returns the string hello"""
return "Hello!"
say_hello. doc # 'A simple function that returns the string hello'
Function Extend
* And As Parameters
args
A special operator we can pass to functions
Gathers remaining arguments as a tuple
Example :
def sum_all_values(*args)
total = 0
for val in args:
total += val
return total
sum_all_values(1, 2, 3) # 6
sum_all_values(1, 2, 3, 4, 5) # 15
def ensure_correct_info(*args)
if "Colt" in args and "Steele" in args:
return "Welcome back Colt!"
kwargs
A special operator we can pass to functions
Example :
Parameter Ordering
1. Parameters
2. *args
3. Default Parameters
4. **kwargs
Tuple Unpacking
Using * as an Argument
Argument Unpacking
def sum_all_values(*args)
# there's a built in sum function - we'll see more later!
return sum(args)
sum_all_values(*[1, 2, 3, 4]) # 10
sum_all_values(*(1, 2, 3, 4)) # 10
Dictionary Unpacking
Using ** as an Argument
display_names(names) # nope
def first_function()
return 'Hello!'
first_function() # 'Hello!'
first_lambda = lambda x: x + 5
first_lambda(10) # 15
Lambda Syntax
lambda parameters : body of function
add_values = lambda x, y: x + y
multiply_values = lambda x, y: x + y
add_values(10, 20) # 30
Map
Syntax Structure
map(function, iterable)
l = [1, 2, 3, 4]
evens # [2, 4, 6, 8]
Another Example :
l = [1,2,3,4]
evens # [2,4,6,8]
names = [
{'first':'Rusty', 'last': 'Steele'},
{'first':'Colt', 'last': 'Steele', },
{'first':'Blue', 'last': 'Steele', }
]
Filter
There is a lambda for each value in the iterable.
Returns filter object which can be converted into other iterables
The object contains only the values that return true to the lambda
l = [1,2,3,4]
evens # [2,4]
users = [
{"username": "samuel", "tweets": ["I love cake", "I love pie", "hello
world!"]},
{"username": "katie", "tweets": ["I love my cat"]},
{"username": "jeff", "tweets": []},
{"username": "bob123", "tweets": []},
{"username": "doggo_luvr", "tweets": ["dogs are the best", "I'm hungry"]},
{"username": "guitar_gal", "tweets": []}
]
Built-In Functions
all()
Return True if all elements of the iterable are truthy (or if the iterable is
empty)
all([0,1,2,3]) # False
any()
Return True if any element of the iterable is truthy. If the iterable is empty,
return False.
any([0, 1, 2, 3]) # True
sorted()
Returns a new sorted list from the items in iterable
more_numbers = [6,1,8,2]
sorted(more_numbers) # [1, 2, 6, 8]
print(more_numbers) # [6, 1, 8, 2]
users = [
{"username": "samuel", "tweets": ["I love cake", "I love pie", "hello
world!"]},
{"username": "katie", "tweets": ["I love my cat"]},
{"username": "jeff", "tweets": [], "color": "purple"},
{"username": "bob123", "tweets": [], "num": 10, "color": "teal"},
{"username": "doggo_luvr", "tweets": ["dogs are the best", "I'm hungry"]},
{"username": "guitar_gal", "tweets": []}
]
Return the largest item in an iterable or the largest of two or more arguments.
# max (strings, dicts with same keys)
max([3,4,1,2]) # 4
max((1,2,3,4)) # 4
max('awesome') # 'w'
max({1:'a', 3:'c', 2:'b'}) # 3
Min
min([3,4,1,2]) # 1
min((1,2,3,4)) # 1
min('awesome') # 'a'
min({1:'a', 3:'c', 2:'b'}) # 1
Exercise
songs = [
{"title": "happy birthday", "playcount": 1},
{"title": "Survive", "playcount": 6},
{"title": "YMCA", "playcount": 99},
{"title": "Toxic", "playcount": 31}
]
reversed()
Return a reverse iterator.
more_numbers = [6, 1, 8, 2]
reversed(more_numbers) # <list_reverseiterator at 0 1049f7da0>
print(list(reversed(more_numbers))) # [2, 8, 1, 6]
abs()
Return the absolute value of a number. The argument may be an integer or a
floating point number.
abs(-5) # 5
abs(5) # 5
sum()
Takes an iterable and an optional start.
Returns the sum of start and the items of an iterable from left to right and
returns the total.
start defaults to 0
sum([1,2,3,4]) # 10
sum([1,2,3,4], -10) # 0
round()
Return number rounded to ndigits precision after the decimal point. If ndigits
is omitted or is None, it returns the nearest integer to its input.
round(10.2) # 10
round(1.212121, 2) # 1.21
zip()
Make an iterator that aggregates elements from each of the iterables.
Returns an iterator of tuples, where the i-th tuple contains the i-th
element from each of the argument sequences or iterables.
The iterator stops when the shortest input iterable is exhausted.
dict(first_zip) # {1 4, 2 5, 3 6}
five_by_two = [(0, 1), (1, 2), (2, 3), (3, 4), (4, 5)]
list(zip(*five_by_two))
midterms = [80,91,78]
finals = [98,89,53]
students = ['dan', 'ang', 'kate']