Codecademy Logo

Functions

Print Cheatsheet

Functions

Some tasks need to be performed multiple times within a program. Rather than rewrite the same code in multiple places, a function may be defined using the def keyword. Function definitions may include parameters, providing data input to the function.

Functions may return a value using the return keyword followed by the value to return.

# Define a function my_function() with parameter x
def my_function(x):
return x + 1
# Invoke the function
print(my_function(2)) # Output: 3
print(my_function(3 + 5)) # Output: 9

Function Keyword Arguments

Python functions can be defined with named arguments which may have default values provided. When function arguments are passed using their names, they are referred to as keyword arguments. The use of keyword arguments when calling a function allows the arguments to be passed in any order — not just the order that they were defined in the function. If the function is invoked without a value for a specific argument, the default value will be used.

def findvolume(length=1, width=1, depth=1):
print("Length = " + str(length))
print("Width = " + str(width))
print("Depth = " + str(depth))
return length * width * depth;
findvolume(1, 2, 3)
findvolume(length=5, depth=2, width=4)
findvolume(2, depth=3, width=4)

Function Parameters

Sometimes functions require input to provide data for their code. This input is defined using parameters.

Parameters are variables that are defined in the function definition. They are assigned the values which were passed as arguments when the function was called, elsewhere in the code.

For example, the function definition defines parameters for a character, a setting, and a skill, which are used as inputs to write the first sentence of a book.

def write_a_book(character, setting, special_skill):
print(character + " is in " +
setting + " practicing her " +
special_skill)

Function Arguments

Parameters in python are variables — placeholders for the actual values the function needs. When the function is called, these values are passed in as arguments.

For example, the arguments passed into the function .sales() are the “The Farmer’s Market”, “toothpaste”, and “$1” which correspond to the parameters grocery_store, item_on_sale, and cost.

def sales(grocery_store, item_on_sale, cost):
print(grocery_store + " is selling " + item_on_sale + " for " + cost)
sales("The Farmer’s Market", "toothpaste", "$1")

Returning Value from Function

A return keyword is used to return a value from a Python function. The value returned from a function can be assigned to a variable which can then be used in the program.

In the example, the function check_leap_year returns a string which indicates if the passed parameter is a leap year or not.

def check_leap_year(year):
if year % 4 == 0:
return str(year) + " is a leap year."
else:
return str(year) + " is not a leap year."
year_to_check = 2018
returned_value = check_leap_year(year_to_check)
print(returned_value) # 2018 is not a leap year.

Multiple Parameters

Python functions can have multiple parameters. Just as you wouldn’t go to school without both a backpack and a pencil case, functions may also need more than one input to carry out their operations.

To define a function with multiple parameters, parameter names are placed one after another, separated by commas, within the parentheses of the function definition.

def ready_for_school(backpack, pencil_case):
if (backpack == 'full' and pencil_case == 'full'):
print ("I'm ready for school!")

Calling Functions

Python uses simple syntax to use, invoke, or call a preexisting function. A function can be called by writing the name of it, followed by parentheses.

For example, the code provided would call the doHomework() method.

doHomework()

Recursion in Python

In Python, a recursive function accepts an argument and includes a condition to check whether it matches the base case. A recursive function has:

  • Base Case - a condition that evaluates the current input to stop the recursion from continuing.
  • Recursive Step - one or more calls to the recursive function to bring the input closer to the base case.
def countdown(value):
if value <= 0: #base case
print("done")
else:
print(value)
countdown(value-1) #recursive case

Recursive Step in Recursive Function

A recursive function should have a recursive step which calls the recursive function with some input that brings it closer to its base case. In the example, the recursive step is the call to countdown() with a decremented value.

def countdown(value):
if value <= 0:
print("done")
else:
print(value)
countdown(value-1) #recursive step

Base Case of a Recursive Function

A recursive function should have a base case with a condition that stops the function from recursing indefinitely. In the example, the base case is a condition evaluating a negative or zero value to be true.

function countdown(value)
if value is negative or zero
print "done"
otherwise if value is greater than zero
print value
call countdown with (value-1)

Lambda Functions

Lambda Functions

A lambda function in Python is a simple, anonymous function that is defined without a name. Lambda functions are useful when we want to write a quick function in one line that can be combined with other built-in functions such as map(), filter(), and apply(). This is the syntax to define lambda functions:

lambda argument(s): expression