0% found this document useful (0 votes)
43 views

Learn Python 3 - Functions

Functions allow code to be reused by defining blocks of code that can be executed multiple times by calling the function. Functions can take parameters as input and return values. Parameters act as local variables within the function. Code within a function is indented and variables defined inside a function are local to that function while variables defined outside have global scope.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
43 views

Learn Python 3 - Functions

Functions allow code to be reused by defining blocks of code that can be executed multiple times by calling the function. Functions can take parameters as input and return values. Parameters act as local variables within the function. Code within a function is indented and variables defined inside a function are local to that function while variables defined outside have global scope.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 4

Cheatsheets / Learn Python 3

Functions
Function Parameters
Sometimes functions require input to provide data for
their code. This input is de ned using parameters. def write_a_book(character, setting,
Parameters are variables that are de ned in the special_skill):
function de nition. They are assigned the values which   print(character + " is in " + 
were passed as arguments when the function was
        setting + " practicing her " + 
called, elsewhere in the code.
        special_skill)
For example, the function de nition de nes parameters
for a character, a setting, and a skill, which are used as
inputs to write the rst sentence of a book.

Multiple Parameters
Python functions can have multiple parameters. Just as
you wouldn’t go to school without both a backpack and def ready_for_school(backpack, pencil_case):
a pencil case, functions may also need more than one   if (backpack == 'full' and pencil_case ==
input to carry out their operations. 'full'):
To de ne a function with multiple parameters,
    print ("I'm ready for school!")
parameter names are placed one after another,
separated by commas, within the parentheses of the
function de nition.

Functions
Some tasks need to be performed multiple times within
a program. Rather than rewrite the same code in # Define a function my_function() with
multiple places, a function may be de ned using the parameter x
def keyword. Function de nitions may include
parameters, providing data input to the function. def my_function(x):
Functions may return a value using the return keyword
  return x + 1
followed by the value to return.

# Invoke the function

print(my_function(2))      # Output: 3
print(my_function(3 + 5))  # Output: 9
Function Indentation
Python uses indentation to identify blocks of code.
Code within the same block should be indented at the # Indentation is used to identify code blocks
same level. A Python function is one type of code
block. All code under a function declaration should be def testfunction(number):
indented to identify it as part of the function. There can   # This code is part of testfunction
be additional indentation within a function to handle
  print("Inside the testfunction")
other statements such as for and if so long as the
  sum = 0
lines are not indented less than the rst line of the
  for x in range(number):
function code.
    # More indentation because 'for' has
a code block
    # but still part of he function
    sum += x
  return sum
print("This is not part of testfunction")

Calling Functions
Python uses simple syntax to use, invoke, or call a
preexisting function. A function can be called by writing doHomework()
the name of it, followed by parentheses.
For example, the code provided would call the
doHomework() method.

Function Arguments
Parameters in python are variables — placeholders for
the actual values the function needs. When the def sales(grocery_store, item_on_sale, cost):
function is called, these values are passed in as   print(grocery_store + " is selling "
arguments. + item_on_sale + " for " + cost)
For example, the arguments passed into the function
.sales() are the “The Farmer’s Market”, “toothpaste”,
sales("The Farmer’s Market", "toothpaste",
and “$1” which correspond to the parameters
"$1")
grocery_store , item_on_sale , and cost .

Function Keyword Arguments


Python functions can be de ned with named
arguments which may have default values provided. def findvolume(length=1, width=1, depth=1):
When function arguments are passed using their   print("Length = " + str(length))
names, they are referred to as keyword arguments. The   print("Width = " + str(width))
use of keyword arguments when calling a function
  print("Depth = " + str(depth))
allows the arguments to be passed in any order — not
  return length * width * depth;
just the order that they were de ned in the function. If
the function is invoked without a value for a speci c
findvolume(1, 2, 3)
argument, the default value will be used.
findvolume(length=5, depth=2, width=4)
findvolume(2, depth=3, width=4)
Returning Multiple Values
Python functions are able to return multiple values
using one return statement. All values that should be def square_point(x, y, z):
returned are listed after the return keyword and are   x_squared = x * x
separated by commas.   y_squared = y * y
In the example, the function square_point() returns   z_squared = z * z
x_squared , y_squared , and z_squared .
  # Return all three values:
  return x_squared, y_squared, z_squared

three_squared, four_squared, five_squared


= square_point(3, 4, 5)

The Scope of Variables


In Python, a variable de ned inside a function is called
a local variable. It cannot be used outside of the scope a = 5
of the function, and attempting to do so without
de ning the variable outside of the function will cause def f1():
an error.
  a = 2
In the example, the variable a is de ned both inside
  print(a)
and outside of the function. When the function f1() is
  
implemented, a is printed as 2 because it is locally
print(a)   # Will print 5
de ned to be so. However, when printing a outside of
the function, a is printed as 5 because it is f1()       # Will print 2
implemented outside of the scope of the function.

Returning Value from Function


A return keyword is used to return a value from a
Python function. The value returned from a function def check_leap_year(year):
can be assigned to a variable which can then be used in   if year % 4 == 0:
the program.     return str(year) + " is a leap year."
In the example, the function check_leap_year returns a   else:
string which indicates if the passed parameter is a leap
    return str(year) + " is not a leap year."
year or not.

year_to_check = 2018
returned_value
= check_leap_year(year_to_check)
print(returned_value) # 2018 is not a leap
year.
Global Variables
A variable that is de ned outside of a function is called
a global variable. It can be accessed inside the body of a = "Hello"
a function.
In the example, the variable a is a global variable def prints_a():
because it is de ned outside of the function prints_a .
  print(a)
It is therefore accessible to prints_a , which will print
  
the value of a .
# will print "Hello"
prints_a()

Parameters as Local Variables


Function parameters behave identically to a function’s
local variables. They are initialized with the values def my_function(value):
passed into the function when it was called.   print(value)   
Like local variables, parameters cannot be referenced   
from outside the scope of the function. # Pass the value 7 into the function
In the example, the parameter value is de ned as part
my_function(7)
of the de nition of my_function , and therefore can only
be accessed within my_function . Attempting to print the
# Causes an error as `value` no longer exists
contents of value from outside the function causes an
error. print(value)

You might also like