This session is all about functions → creating them, passing arguments, scope, and the functional-programming tools (lambda, map, filter, reduce).
A function is a reusable block of code. The triple-quoted text right under the def line is a docstring → a short description of what the function does.
def is_even(num):
"""
This function returns if a given number is odd or even
input - any valid integer
output - odd/even
created on - 16th Nov 2022
"""
if type(num) == int:
if num % 2 == 0:
return 'even'
else:
return 'odd'
else:
return 'pagal hai kya?'
Calling it in a loop:
for i in range(1,11):
x = is_even(i)
print(x)
# odd
# even
# odd
# even
# ... (keeps alternating up to 10)
Every function's docstring is stored in __doc__. Even built-in types have one:
print(type.__doc__)
# type(object_or_name, bases, dict)
# type(object) -> the object's type
# type(name, bases, dict) -> a new type
(The -> here is part of Python's own docstring text, not a connector.)
There are two sides to a function: the creator and the user. The creator thinks about edge cases (like someone passing a string instead of a number), the user just calls it and gets a result.
is_even('hello') # 'pagal hai kya?' (the else branch handles non-integers)
num above).'hello' or 4).Three kinds: default, positional, and keyword.
def power(a=1, b=1): # a and b have DEFAULT values
return a**b
power() # 1 (uses the defaults, 1**1)
power(2,3) # 8 (positional: a=2, b=3)
power(b=3, a=2) # 8 (keyword: name them directly, order does not matter)