Functions

Write and call a function

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

common function errors include:

  • Forgetting closing parenthesis
  • Forgetting commas between each argument

Scope of variables

Local variables

Variable defined inside a function is a local variable. It cannot be used outside of the scope of the function.

Global Variables

Variable defined outside of a function is a global variable and it can be accessed inside the body of a function.

Returning Multiple Values

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

Lambda Functions

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:

  • Lambda functions are great when you need to use a function once.
  • Save the work of defining a function

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
  • The function is stored in a variable called contains_a
  • Declare lambda function with an input called word (lambda word:)
  • Return True if this statement is true
  • Return False if this statement is not true

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"