To avoid rewriting the same code in multiple places, we use functions.
A function is defined with def()
keyword.
Python uses indentation to identify blocks of code. Code within the same block should be indented at the same level.
def function_name(input1, input2):
# do something with the inputs
return output
function_name()
For example
def sum(x,y):
return x + y
print(sum(2,4)) # Output: 6
common function errors include:
Variable defined inside a function is a local variable. It cannot be used outside of the scope of the function.
Variable defined outside of a function is a global variable and it can be accessed inside the body of a function.
Python functions are able to return multiple values using one return statement. All values that should be returned are listed after the return keyword and are separated by commas.
def calculation(x, y):
addition = x + y
subtraction = x - y
return addition, subtraction # Return all two values
A lambda function is a one-line shorthand for function. It allows us to efficiently run an expression and produce an output for a specific task
Benefits:
Syntax
lambda arguments : expression
Example 1 Create a lambda function named contains_a that takes an input word and returns True if the input contains the letter ‘a’. Otherwise, return False.
contains_a = lambda word: "a" in word
Example 2 The function will return your input minus 1 if your input is positive or 0, and otherwise will return your input plus 1.
add_subtract = lambda num: num - 1 if num >= 0 else num + 1
Example 3 Create a lambda function named even_odd that takes an integer named num. If num is even, return “even”. If num is odd, return “odd”
even_odd = lambda num: "even" if num % 2 == 0 else "odd"