Python - Functions¶
Functions¶
Specify optional parameters in the end. Specify the default values for optional parameters with = value notation
def func_name(arg1, arg2=None):
operations
return value
def func_add_numbers(num1, num2=10):
return (num1 + num2) # return can be called as a statement or as a function
func_add_numbers(2)
12
func_add_numbers(2,34)
36
func_add_numbers()
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) /var/folders/d8/93856prx6tj3x7vdn97z2ps40000gn/T/ipykernel_43270/1819578982.py in <module> ----> 1 func_add_numbers() TypeError: func_add_numbers() missing 1 required positional argument: 'num1'
Type hinting¶
Starting at Python 3.7 you can provide hits to specify argument data type
def func_add_numbers(a: int, b: int = 10) -> int:
sum = a + b
return sum
print(func_add_numbers(5, 4))
print(func_add_numbers(5))
print(func_add_numbers(5.5, 4.3)) # will still work as types are only hinted not enforced
9 15 9.8
Productivity hacks for Python¶
These are good to know shortcuts and methods that will reduce the need for writing explicit loops and condition checks. The comprehensions explained in cheat sheet 1 is a start, and falls under this category.
Productivity functions
def doubler(input_number):
return input_number*2
doubler(45)
90
temp_fn = lambda arg : arg*2
temp_fn(55)
110
type(temp_fn)
function
It looks silly now, but lambdas work great with map
and other productivity functions. You can have other methods and functions that do the heavy lifting and call them in a particular order from a lambda
map function¶
The map
function will perform an operation on all elements of an input list. You can execute a function on all elements of a list without a loop, like a comprehension.
map(function, sequence) --> applies the function for each element in the sequence. The return sequence if of same length as input sequence
l1 = [1,2,3,4,5,6,7]
#to double elements in this list using list comp
l1_double = [i*2 for i in l1]
l1_double
[2, 4, 6, 8, 10, 12, 14]
#double using map and a function
l1_double_2 = list(map(doubler, l1))
l1_double_2
[2, 4, 6, 8, 10, 12, 14]
#double using map and a lambda function
l1_double_3 = list(map(lambda arg:arg*2, l1))
l1_double_3
[2, 4, 6, 8, 10, 12, 14]
filter function¶
filter
function is used to filter out elements in a sequence based on a condition
filter(function, sequence) --> applies the function for each element in sequence, but the return sequence is same or smaller than input based on the condition in the `function`.
The function should return a bool
#find only the odd numbers --> list comp way
l1_odd = [i for i in l1 if i%2 > 0]
l1_odd
[1, 3, 5, 7]
# find only odd numbers --> filter with lambda way
l1_odd_2 = list(filter(lambda arg:arg%2>0, l1))
l1_odd_2
[1, 3, 5, 7]