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.

Snapshot of working with functions.

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

Create a Function That Returns Multiple Values

Create a Function with Optional Parameters

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

Snapshot of 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

Snapshot of looking at an example of a function’s Syntax.

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

Snapshot of 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:

  • Functions with both parameters and return values
  • Functions with parameters but no return values
  • Function with no parameters but with return values
  • Functions with no parameters and no return values

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.

Snapshot of functions with both parameters and return values.

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

abs()

Returns the absolute value of the specified number.

aiter()

Returns an asynchronous iterator for an asynchronous iterable.

all()

Returns True if all elements of the specified iterable are True.

anext()

Returns the next item from the specified asynchronous iterator.

any()

Returns True if any element of the specified iterable is True.

ascii()

Returns a string containing a printable reproduction of the object with non-ASCII characters escaped using x, u, and U escape codes.

bin()

Returns a binary string for the value the specified integer, prefixed with 0b.

bool()

Returns the Boolean value — True or False — of the specified item.

breakpoint()

Switches to the Python debugger.

bytearray()

Returns a bytearray object containing a new array of bytes.

bytes()

Returns a new bytes object.

callable()

Returns True if the object appears callable.

chr()

Returns the string for the character representing the specified Unicode code point.

classmethod()

Returns a class method from the specified method.

compile()

Returns a code object compiled from the specified source file.

complex()

Returns a complex number from the specified real value and imaginary value.

delattr()

Returns the specified object with the specified attribute deleted.

dict()

Returns a new dictionary.

dir()

Returns the list of names in the current local scope or in the specified scope.

divmod()

Returns the quotient and remainder of the two specified numbers divided using integer division.

enumerate()

Returns an enumerate object from the specified iterable.

eval()

Returns the evaluated expression from the specified expression and arguments.

exec()

Executes the specified Python code object.

filter()

Returns an iterator constructed from the specified function and iterable.

float()

Returns a floating-point number from the specified number or string.

format()

Returns a formatted representation of the specified value.

frozenset()

Returns a new frozenset object.

getattr()

Returns the value of the specified attribute of the given object.

globals()

Returns the dictionary for the current module namespace.

hasattr()

Returns True if the specified object includes the specified attribute.

hash()

Returns the integer hash value of the object, if the object has one.

help()

Calls Python’s built-in help system.

hex()

Returns the hexadecimal string, prefixed with 0x, for the specified integer.

id()

Returns the specified object’s identity, a unique integer.

input()

Prompts the user for input.

int()

Returns an integer from the specified number or string.

isinstance()

Returns True if the specified object is an instance of the specified class.

issubclass()

Returns True if the specified object is a subclass of the specified class.

iter()

Returns an iterator object for the specified object.

len()

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.

list()

Returns a list, tuple, or range.

locals()

Returns the updated dictionary for the current local symbol table.

map()

Returns an iterator showing the specified function applied to every item in the specified iterable.

max()

Returns the largest item in the specified iterable or group.

memoryview()

Returns a memory view object for the specified object.

min()

Returns the smallest item in the specified iterable or group.

next()

Returns the next item from the specified iterator.

object()

Returns a new object of the object class, the base for all other classes.

oct()

Returns an octal string, prefixed with 0o, for the specified integer.

open()

Opens the specified file and returns a file object representing it.

ord()

Returns an integer representing the Unicode code point for the specified string.

pow()

Returns the specified base number raised to the specified power, optionally using a modulo.

print()

Prints the specified objects to the text stream file.

property()

Returns the specified property.

range()

Returns a range object.

repr()

Returns a string containing a printable representation of the specified object.

reversed()

Returns a reverse iterator for the specified object.

round()

Returns the specified number rounded to the specified precision.

set()

Returns a new set object.

setattr()

Returns the specified object with the specified attribute set.

slice()

Returns a slice object for the given set of indices.

sorted()

Returns a sorted list from the specified iterable.

staticmethod()

Returns a static method from the specified method.

str()

Returns a string from the specified object.

sum()

Returns the total of items in the specified iterable.

super()

Returns a proxy object for delegating method calls to a parent or sibling class.

tuple()

Returns a tuple from the specified iterable.

type()

Returns either the type of the specified object or a new type object.

vars()

Returns the __dict__ attribute for the specified object.

zip()

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

Snapshot of create a function with parameters and a return.

001.eps Open a terminal window and launch Python.

dga.eps The Python prompt appears.

002.eps Type the following function header, and then press Ent:

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.

003.eps Type the following statement, which divides the percent value by 100, assigning it back to percent. Press Ent.

percent = percent / 100

Snapshot of type the following statement, which declares the variable tip.

004.eps Type the following statement, which declares the variable tip and assigns to it the product of bill and percent. Press Ent.

tip = bill * percent

005.eps Type the following statement, which returns tip to the calling code. Press Ent once, and then press Ent again to end the function.

return tip

006.eps Type the following statement, which uses the print() function to display the result of calculating a 15% tip on a $50 bill. Press Ent.

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

Snapshot of create a function with a parameter but no return.

001.eps Open a terminal window and launch Python.

dga.eps The Python prompt appears.

002.eps Type the following function header, which declares the function name and a parameter called liters, and then press Ent.

def convert_liters_to_pints(liters):

003.eps 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 Ent.

pints = 2.11338 * liters

004.eps Type the following statement, which uses the round() function to round pints down to one decimal place, and then press Ent:

pints = round(pints, 1)

Snapshot of which calls the function.

005.eps Type the following statement, which creates a variable named msg and assigns to it a string derived from liters plus literal text. Press Ent.

msg = str(liters) + " liters is "

006.eps Type the following statement, which completes the msg string by adding a string derived from pints plus literal text. Press Ent.

msg = msg + str(pints) + " pints."

007.eps Type the following statement, which uses the print() function to display msg. Press Ent twice.

print(msg)

008.eps Type the following statement, which calls the function and supplies the liters value:

convert_liters_to_pints(3.75)

dgb.eps 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

Snapshot of

001.eps Open Visual Studio Code and create a new Python script.

002.eps Type the following function header, and then press Ent.

def generate_name():

003.eps 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.

Snapshot of create a function with a parameter but no return.

004.eps Type the following statement, which creates a variable named first and assigns to it a list of first names. Press Ent.

first = ["Al", "Bo", "Cy", "Dot", "Ed", "Em"]

005.eps Type the following statement, which creates a variable named middle and assigns to it a list of initials. Press Ent.

middle = ["A.", "B.", "C.", "D.", "E.", "F."]

006.eps Type the following statement, which creates a variable named last and assigns to it a list of last names. Press Ent.

last = ["Adams", "Bain", "Col", "Dunn", "Ely"]

Snapshot of type the following statement, which creates a variable named first.

007.eps Type the following statement, which imports the choice item from the random module, and then press Ent.

from random import choice

008.eps Type the following statement, which creates the variable cname and assigns to it a random item chosen from the first list. Press Ent.

cname = choice(first)

009.eps Type the following statement, which adds to cname a space and a random item chosen from the middle list. Press Ent.

cname = cname + " " + choice(middle)

Snapshot of type the following statement, which imports the choice item.

010.eps Type the following statement, which adds to cname another space and a random item chosen from the last list. Press Ent.

cname = cname + " " + choice(last)

011.eps Type the following statement to return cname, and then press Ent twice to end the function.

return cname

012.eps Press Bksp 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())

013.eps Click Run Python File in Terminal (9781119860259-ma040).

Visual Studio Code displays the Terminal pane.

dga.eps 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

Snapshot of run python file in terminal.

001.eps Open a terminal window and launch Python.

dga.eps The Python prompt appears.

002.eps Type the following function header, which specifies no parameter, and then press Ent.

def show_username():

003.eps Type the following two-line function definition, pressing Ent at the end of each line:

"""This sample function uses no parameter

and returns no value."""

004.eps Type the following statement, which imports the getuser() method from the getpass module, and then press Ent:

from getpass import getuser

Snapshot of function runs and displays the message including the username.

005.eps Type the following statement, which creates the variable you and assigns a string of text to it. Press Ent.

you = "You are logged in as "

006.eps Type the following statement, which completes the you string by adding the username, returned by the getuser() method, and a period. Press Ent.

you = you + getuser() + "."

007.eps Type the following statement, which uses the print() function to display the you string. Press Ent twice.

print(you)

008.eps Type the function’s name, and then press Ent.

dgb.eps 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

Snapshot of create a function that returns multiple values.

001.eps Open a terminal window and launch Python.

dga.eps The Python prompt appears.

002.eps Type the following function header, which declares the function with one parameter, miles. Press Ent.

def convert_miles_yards_feet_inches(miles):

003.eps Type the following statement, which creates the variable yards and assigns to it the result of multiplying miles by 1760. Press Ent.

yards = miles * 1760

004.eps Type the following statement, which creates the variable feet and assigns to it the result of multiplying miles by 5280. Press Ent.

feet = miles * 5280

Snapshot of python displays the resulting tuple.

005.eps Type the following statement, which creates the variable inches and assigns to it the result of multiplying miles by 63,360. Press Ent.

inches = miles * 63360

006.eps Type the following return statement, which returns yards, feet, and inches. Press Ent.

return yards, feet, inches

007.eps Type the following statement, which uses the print() function to display the result of calling the function with the argument 2, and then press Ent.

print(convert_miles_yards_feet_inches(2))

dgb.eps 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

Snapshot of create a function with optional parameters.

001.eps Open a terminal window and launch Python.

dga.eps The Python prompt appears.

002.eps 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 Ent.

def parlay(odds1, odds2, odds3 = None, odds4 = None, odds5 = None):

003.eps Type the function description, and then press Ent.

"""Calculate the odds for a parlay that contains two, three, four, or five bets"""

Snapshot of type the following statement, which declares the variable p.

004.eps Type the following statement, which declares the variable p and assigns to it the result of multiplying odds1 and odds2. Press Ent.

p = odds1 * odds2

005.eps Type the following if statement, which checks whether odds3 has the value None and, if not, multiplies p by odds3. Press Ent at the end of each line.

if odds3 != None:

p = p * odds3

Snapshot of type two similar if statements for odds4 and odds5.

006.eps Type two similar if statements for odds4 and odds5, again pressing Ent at the end of each line:

if odds4 != None:

p = p * odds4

if odds5 != None:

p = p * odds5

007.eps Type the following return statement, which causes the function to return the value of p to the calling code, and then press Ent.

return p

008.eps Press Ent again to end the function.

The Python prompt appears again.

Snapshot of python displays the accumulated odds for the fourfold bet.

009.eps 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 Ent.

print(parlay(1.72, 2, 3.6, 1.72))

Python displays the accumulated odds for the fourfold bet.

010.eps Press Arkup to reenter the previous statement, but this time edit the end to include a fifth argument. Press Ent.

print(parlay(1.72, 2, 3.6, 1.72, 4))

Python displays the accumulated odds for the fivefold bet — 85.20192 for the example.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.141.45.253