CHAPTER 8
Working with Functions
As in other programming languages, a function in Python is a stand-alone section of code that performs a particular task. In this chapter, you learn how functions work, put Python’s built-in functions to use, and create custom functions of your own.
Understanding Functions and Their Syntax
Understanding Function Parameters and Returns
Using Python’s Built-In Functions
Create a Function with Parameters and a Return
Create a Function with a Parameter But No Return
Create a Function with No Parameters But a Return
Create a Function with No Parameters and No Return
Understanding Functions and Their Syntax
A function is a stand-alone section of code that performs a particular task. For example, as you have seen earlier in this book, the input()
function prompts the user to input text, while the print()
function displays information on-screen. Python includes around 70 built-in functions that you can use immediately, and you can access other prebuilt functions by importing the modules that contain them. You can also create your own custom functions to perform operations that Python’s existing functions do not cover.
Understanding the Syntax of a Function
In Python, a function’s syntax looks like the following pseudocode and the nearby drawing:
def function_name(parameters):
"""function_description"""
statements
return [expression]
The following list explains the components of a function’s syntax:
def
. This keyword, short for definition, begins the function header.function_name
. Each function must have a name that is unique in its context so that your code can refer to the function unambiguously.parameters
. Parameters are named items used to pass values to a function. The values passed are called arguments. Parameters are optional: Some functions have parameters, whereas other functions have none.:
(colon). The colon denotes the end of the function header. After the colon, the function’s contents are indented, usually by four spaces, to indicate that they are subordinate to the function header.function_description
. This description is a comment describing what the function does. The description is optional but is usually helpful. It is sometimes called the documentation string or docstring.statements
. The statements specify the actions that the function performs.return [expression]
. The return
statement ends the function and returns the function’s result to the code that called the function. If the return
statement specifies an expression, Python returns that expression. If the return
specifies no expression, Python returns None
, a special value. The return
statement is optional, so some functions do not have it. Python returns None
if there is no return
statement.Looking at an Example of a Function’s Syntax
The following code shows a custom function. The nearby drawing breaks down the function’s components.
def odd_even(n):
"""Function to return 'Odd' or 'Even' for a specified 'n' input."""
if int(n)%2 == 0:
odd_or_even = "Even"
else:
odd_or_even = "Odd"
return odd_or_even
The function begins with the def
keyword, after which comes the function’s name, odd_even
; its parameter, n
, in parentheses; and the colon that ends the function header.
The second and third lines contain the function’s description in a comment delimited by three double quotes. After those lines is an if… else
statement that creates the function’s output, either Even
or Odd
, which is stored in the variable odd_or_even
. In the final line, the return
statement returns the value in odd_or_even
.
Once your code has defined this function, you can call the function by entering its name and the argument for the required parameter, n
. For example, the following statement creates the variable x1
and assigns to it the function’s output for the number the user types when prompted:
x1 = odd_even(input("Enter a number: "))
The function returns Even
for an even number and Odd
for an odd number.
Understanding Function Parameters and Returns
Most functions use one or more parameters, named items that receive arguments containing the values the user wants the function to manipulate. Parameters can be either required or optional, and a function may use both required parameters and optional parameters. However, some functions use no parameters at all.
Similarly, most functions return one or more values to the code that called them. However, some functions return no values.
Understanding the Four Types of Functions
The combination of parameters-or-no-parameters and values-or-no-values gives four types of functions in Python:
The following subsections explore these different types, giving brief examples.
Functions with Both Parameters and Return Values
Many functions both use parameters to accept input and return one or more values after running.
For example, the built-in abs()
function returns the absolute value of a number, the non-negative value of a number even if it has a minus sign. The abs()
function has one parameter, to which you provide an argument containing the number for which to return the absolute value. For example, abs(-2)
returns 2
, and abs(-99*2/50 + 5)
returns 1.04
.
Functions with Parameters But No Return Values
Some functions use one or more parameters to accept input but return no values. Instead, such functions typically perform an action.
For example, Python’s built-in print()
function displays text on-screen rather than returning a value. This function uses one parameter, the string or other item you want to display. For example, print("The quick brown fox, etc.")
displays the text The quick brown fox, etc.
provided as the argument for its parameter.
Functions with No Parameters But with Return Values
Some functions use no parameters but do return one or more values. For example, the built-in globals()
function returns the dictionary for the current module namespace, the virtual area in which the module is operating. Here is an example of running the globals()
function:
>>> globals()
{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>}
>>>
Functions with No Parameters and No Return Values
Some functions — relatively few — use no parameters and return no values. Such a function may either generate or gather its own data automatically or prompt the user to enter data. Rather than returning one or more values to the calling code, the function may display output — for example, by using the print()
function.
None of Python’s built-in functions falls into this category. Here is an example of a custom function that uses no parameters and returns no values:
def day_of_week():
from datetime import datetime
thisday = datetime.today().strftime("%A")
print(thisday)
This day_of_week()
function imports the datetime
object from the datetime
module. The second line creates a variable called thisday
and assigns to it a formatted string returned using the today()
method of the datetime
object. The third line uses the print()
function to display the day, such as Wednesday
.
Using Python’s Built-In Functions
Python includes around 70 built-in functions that you can use immediately without needing to load extra modules. These functions perform a variety of widely useful tasks. Some functions help you create and debug your code. For example, the compile()
function compiles a source file into a code object, the exec()
function executes a code object, and the breakpoint()
function switches to the Python debugger at the specified point in a script. Other functions, such as setattr()
and delattr()
, enable you to manipulate the attributes of objects.
Table 8-1 explains Python’s built-in functions.
Table 8-1: Python’s Built-In Functions
Function Name |
What It Returns or Does |
---|---|
|
Returns the absolute value of the specified number. |
|
Returns an asynchronous iterator for an asynchronous iterable. |
|
Returns |
|
Returns the next item from the specified asynchronous iterator. |
|
Returns |
|
Returns a string containing a printable reproduction of the object with non-ASCII characters escaped using |
|
Returns a binary string for the value the specified integer, prefixed with |
|
Returns the Boolean value — |
|
Switches to the Python debugger. |
|
Returns a |
|
Returns a new |
|
Returns |
|
Returns the string for the character representing the specified Unicode code point. |
|
Returns a class method from the specified method. |
|
Returns a code object compiled from the specified source file. |
|
Returns a complex number from the specified real value and imaginary value. |
|
Returns the specified object with the specified attribute deleted. |
|
Returns a new dictionary. |
|
Returns the list of names in the current local scope or in the specified scope. |
|
Returns the quotient and remainder of the two specified numbers divided using integer division. |
|
Returns an |
|
Returns the evaluated expression from the specified expression and arguments. |
|
Executes the specified Python code object. |
|
Returns an iterator constructed from the specified function and iterable. |
|
Returns a floating-point number from the specified number or string. |
|
Returns a formatted representation of the specified value. |
|
Returns a new |
|
Returns the value of the specified attribute of the given object. |
|
Returns the dictionary for the current module namespace. |
|
Returns |
|
Returns the integer hash value of the object, if the object has one. |
|
Calls Python’s built-in help system. |
|
Returns the hexadecimal string, prefixed with |
|
Returns the specified object’s identity, a unique integer. |
|
Prompts the user for input. |
|
Returns an integer from the specified number or string. |
|
Returns |
|
Returns |
|
Returns an iterator object for the specified object. |
|
Returns the length of the specified object. The length is the number of items the object contains — for example, the number of characters in a string. |
|
Returns a list, tuple, or range. |
|
Returns the updated dictionary for the current local symbol table. |
|
Returns an iterator showing the specified function applied to every item in the specified iterable. |
|
Returns the largest item in the specified iterable or group. |
|
Returns a memory view object for the specified object. |
|
Returns the smallest item in the specified iterable or group. |
|
Returns the next item from the specified iterator. |
|
Returns a new object of the |
|
Returns an octal string, prefixed with |
|
Opens the specified file and returns a file object representing it. |
|
Returns an integer representing the Unicode code point for the specified string. |
|
Returns the specified base number raised to the specified power, optionally using a modulo. |
|
Prints the specified objects to the text stream file. |
|
Returns the specified property. |
|
Returns a |
|
Returns a string containing a printable representation of the specified object. |
|
Returns a reverse iterator for the specified object. |
|
Returns the specified number rounded to the specified precision. |
|
Returns a new |
|
Returns the specified object with the specified attribute set. |
|
Returns a |
|
Returns a sorted list from the specified iterable. |
|
Returns a static method from the specified method. |
|
Returns a string from the specified object. |
|
Returns the total of items in the specified iterable. |
|
Returns a proxy object for delegating method calls to a parent or sibling class. |
|
Returns a tuple from the specified iterable. |
|
Returns either the type of the specified object or a new type object. |
|
Returns the |
|
Returns tuples from the specified iterables. |
Python’s built-in functions include functions for converting values to particular data types. For example, the int()
function returns an integer, the str()
function returns a string, the list()
function returns a list, and the tuple()
function returns a tuple. Similarly, the bin()
, oct()
, and hex()
functions return strings containing binary, octal, and hexadecimal representations of the value supplied.
Other functions that are widely useful include three you have used already in this book. The input()
function prompts the user for input, the open()
function opens a file and returns a file object representing it, and the print()
function displays output.
The following sections provide brief examples of putting some of the most widely used of Python’s built-in functions to use.
Using the input()
Function
The input()
function enables you to prompt the user for input. Python receives the input as a string, but you can cast it to a different data type if needed, as in the following example:
>>> n1 = input("Type a number between 1 and 20: ")
Type a number between 1 and 20: 17
>>> n1
'17'
>>> n1 = int(n1)
>>> n1
17
Using the sorted()
Function
The sorted()
function lets you sort an iterable into either ascending order or descending order. The following example creates a variable named locs
, assigns five place names to it, and then sorts them alphabetically.
>>> locs = ["Cobb", "Berg", "Eden", "Alba", "Dyer"]
>>> sorted(locs)
['Alba', 'Berg', 'Cobb', 'Dyer', 'Eden']
To sort backward, use sorted()
with reverse=True
:
>>> sorted(locs, reverse=True)
['Eden', 'Dyer', 'Cobb', 'Berg', 'Alba']
Returning Binary, Octal, or Hexadecimal Strings
The bin()
function returns a string consisting of the prefix 0b
and the binary value of the specified integer. Similarly, the oct()
function returns a string consisting of the prefix 0o
and the octal value, and the hex()
function returns a string consisting of the prefix 0x
and the hexadecimal value.
For example, bin(100)
returns the string 0b1100100
, oct(100)
returns the string 0o144
, and hex(100)
returns the string 0x64
.
Converting Binary, Octal, or Hexadecimal Strings to Decimal Values
The int()
function enables you to convert a binary, octal, or hexadecimal string to a decimal value. For example, int(0b1100100)
returns 100
.
To convert a binary, octal, or hexadecimal number that is not in string format to a decimal value, use the int()
function, specifying the value as a string and providing the second argument 2
for binary, 8
for octal, or 16
for hexadecimal. For example, int("1100100", 2)
returns 100
from the binary number 1100100
.
Using the print()
Function to Display Information
The print()
function enables you to print objects to the text stream file, giving you an easy way to display information to the user. For example, print("New file created")
displays the text New file created
.
Create a Function with Parameters and a Return
In this section, you create a function that uses parameters and returns a value. The function, calculate_tip
, calculates the amount of a service gratuity. The function uses two required parameters: The bill
parameter accepts the amount of the bill, and the percent
parameter accepts the tip percentage. The function divides percent
by 100
so that the user can enter the percentage as a round number, such as 15
, rather than as the number that actually produces that percentage, such as 0.15
. The function returns a single value, tip
, which contains the amount of the tip.
Create a Function with Parameters and a Return
Open a terminal window and launch Python.
The Python prompt appears.
Type the following function header, and then press :
def calculate_tip(bill, percent):
Note: After the function header, indent each line of the function by four spaces to indicate that the line is part of the function.
Type the following statement, which divides the percent
value by 100
, assigning it back to percent
. Press .
percent = percent / 100
Type the following statement, which declares the variable tip
and assigns to it the product of bill
and percent
. Press .
tip = bill * percent
Type the following statement, which returns tip
to the calling code. Press once, and then press again to end the function.
return tip
Type the following statement, which uses the print()
function to display the result of calculating a 15% tip on a $50 bill. Press .
print(calculate_tip(50,15))
Python returns 7.5
, indicating a $7.50 tip.
Create a Function with a Parameter But No Return
In this section, you create a function that uses a parameter but that returns no values to the code that calls it. Instead of returning values, the function uses the print()
function to display information to the user. The function is called convert_liters_to_pints()
and converts liters to U.S. pints.
To create a function that returns no value explicitly, you can include the return
statement but not specify a return value. Alternatively, you can omit the return
statement. Both approaches have the same effect: The function returns no value explicitly, but implicitly it returns the value None
.
Create a Function with a Parameter But No Return
Open a terminal window and launch Python.
The Python prompt appears.
Type the following function header, which declares the function name and a parameter called liters
, and then press .
def convert_liters_to_pints(liters):
Type the following statement, which creates the variable pints
and assigns to it the result of multiplying the liters
argument by 2.11338
, the appropriate factor. Press .
pints = 2.11338 * liters
Type the following statement, which uses the round()
function to round pints
down to one decimal place, and then press :
pints = round(pints, 1)
Type the following statement, which creates a variable named msg
and assigns to it a string derived from liters
plus literal text. Press .
msg = str(liters) + " liters is "
Type the following statement, which completes the msg
string by adding a string derived from pints
plus literal text. Press .
msg = msg + str(pints) + " pints."
Type the following statement, which uses the print()
function to display msg
. Press twice.
print(msg)
Type the following statement, which calls the function and supplies the liters
value:
convert_liters_to_pints(3.75)
Python displays the result:
3.75 liters is 7.9 pints.
Create a Function with No Parameters But a Return
In this section, you create a function that uses no parameters but that does return a value to the code that calls it. The function is called generate_name()
and returns a name created by combining a random first name, a random middle initial, and a random last name.
For space reasons, the lists of names and the list of initials shown here are unrealistically short. Feel free to extend them with as many names as you wish.
Create a Function with Parameters But No Return
Open Visual Studio Code and create a new Python script.
Type the following function header, and then press .
def generate_name():
Type the following four lines of function description:
# This function returns a character name
# by taking a first name from one list,
# a middle initial from another list,
# and a last name from a third list.
Type the following statement, which creates a variable named first
and assigns to it a list of first names. Press .
first = ["Al", "Bo", "Cy", "Dot", "Ed", "Em"]
Type the following statement, which creates a variable named middle
and assigns to it a list of initials. Press .
middle = ["A.", "B.", "C.", "D.", "E.", "F."]
Type the following statement, which creates a variable named last
and assigns to it a list of last names. Press .
last = ["Adams", "Bain", "Col", "Dunn", "Ely"]
Type the following statement, which imports the choice
item from the random
module, and then press .
from random import choice
Type the following statement, which creates the variable cname
and assigns to it a random item chosen from the first
list. Press .
cname = choice(first)
Type the following statement, which adds to cname
a space and a random item chosen from the middle
list. Press .
cname = cname + " " + choice(middle)
Type the following statement, which adds to cname
another space and a random item chosen from the last
list. Press .
cname = cname + " " + choice(last)
Type the following statement to return cname
, and then press twice to end the function.
return cname
Press to remove the indentation, and then type the following for
loop, which uses range(0,9)
with the print()
function to output ten names.
for i in range(0,9):
print(generate_name())
Click Run Python File in Terminal ().
Visual Studio Code displays the Terminal pane.
The sample names appear.
Create a Function with No Parameters and No Return
A function with no parameters and no return is relatively unusual because it lacks flexibility in both input and output. Without parameters to receive values from arguments passed by the calling code, the function either must contain any values it needs or must derive them from other sources. Without a return value, the function needs to rely on other means of communication, such as using the print()
function to display text.
In this section, you create a parameter-free and return-free function named show_username()
that uses the print()
function to display the username under which the user is currently logged in.
Create a Function with No Parameters and No Return
Open a terminal window and launch Python.
The Python prompt appears.
Type the following function header, which specifies no parameter, and then press .
def show_username():
Type the following two-line function definition, pressing at the end of each line:
"""This sample function uses no parameter
and returns no value."""
Type the following statement, which imports the getuser()
method from the getpass
module, and then press :
from getpass import getuser
Type the following statement, which creates the variable you
and assigns a string of text to it. Press .
you = "You are logged in as "
Type the following statement, which completes the you
string by adding the username, returned by the getuser()
method, and a period. Press .
you = you + getuser() + "."
Type the following statement, which uses the print()
function to display the you
string. Press twice.
print(you)
Type the function’s name, and then press .
The function runs and displays the message including the username.
Create a Function That Returns Multiple Values
Many functions return just a single value, but Python enables you to create functions that return multiple values. In this section, you create a function that uses one required parameter and that returns three values. The function is called convert_miles_yards_feet_inches()
; it uses a parameter called miles
, and it returns the equivalent numbers of yards, feet, and inches.
Create a Function That Returns Multiple Values
Open a terminal window and launch Python.
The Python prompt appears.
Type the following function header, which declares the function with one parameter, miles
. Press .
def convert_miles_yards_feet_inches(miles):
Type the following statement, which creates the variable yards
and assigns to it the result of multiplying miles
by 1760
. Press .
yards = miles * 1760
Type the following statement, which creates the variable feet
and assigns to it the result of multiplying miles
by 5280. Press .
feet = miles * 5280
Type the following statement, which creates the variable inches
and assigns to it the result of multiplying miles
by 63,360. Press .
inches = miles * 63360
Type the following return
statement, which returns yards
, feet
, and inches
. Press .
return yards, feet, inches
Type the following statement, which uses the print()
function to display the result of calling the function with the argument 2
, and then press .
print(convert_miles_yards_feet_inches(2))
Python displays the resulting tuple:
(3520, 10560, 126720)
Create a Function with Optional Parameters
Including optional parameters in a custom function enables you to make your code more flexible. In this section, you create a custom function that calculates the odds for a parlay bet, a cumulative bet on multiple outcomes. The function lets the user calculate the odds for a parlay involving two, three, four, or five bets using decimal odds. The function uses required parameters for the first two bets, because a parlay must have at least two bets. The function uses optional parameters for the remaining three bets, thus allowing the user to include these bets or omit them.
Create a Function with Optional Parameters
Open a terminal window and launch Python.
The Python prompt appears.
Type the following function header, which declares the function parlay
with five parameters, odds1
through odds5
, making the last three parameters optional by assigning the value None
to them. Press .
def parlay(odds1, odds2, odds3 = None, odds4 = None, odds5 = None):
Type the function description, and then press .
"""Calculate the odds for a parlay that contains two, three, four, or five bets"""
Type the following statement, which declares the variable p
and assigns to it the result of multiplying odds1
and odds2
. Press .
p = odds1 * odds2
Type the following if
statement, which checks whether odds3
has the value None
and, if not, multiplies p
by odds3
. Press at the end of each line.
if odds3 != None:
p = p * odds3
Type two similar if
statements for odds4
and odds5
, again pressing at the end of each line:
if odds4 != None:
p = p * odds4
if odds5 != None:
p = p * odds5
Type the following return
statement, which causes the function to return the value of p
to the calling code, and then press .
return p
Press again to end the function.
The Python prompt appears again.
Type the following statement, which uses the print()
function to display the result of calling the parlay()
function and supplying four bets at low odds. Press .
print(parlay(1.72, 2, 3.6, 1.72))
Python displays the accumulated odds for the fourfold bet.
Press to reenter the previous statement, but this time edit the end to include a fifth argument. Press .
print(parlay(1.72, 2, 3.6, 1.72, 4))
Python displays the accumulated odds for the fivefold bet — 85.20192
for the example.
3.141.45.253