Python Functions 2

Python Functions 2 – Built-in Functions

Python has many built-in functions. We described four built-in functions, namely range(), print(), len(), and input() in Python Functions 1 chapter.

The complete list of Python built-in functions is in the Appendix. They can also be referred to in the Python.org link here.

Here we will describe a few more python built-in functions.

Python Format() function

You might ask why use format() function?

Python displays floating-point number results with lots of digits after the decimal point. Normally, you would like to show the results with a lesser number of digits after the decimal.

The format() function allows us to specify the number of digits you would like to display after the decimal in your floating-point result. Revisiting the topic of irrational numbers, we discussed a mathematical constant pi (denoted by the Greek letter π), which is the ratio of a circle’s circumference to its diameter. pi appears in all scientific problems in engineering, mathematics, physics, chemistry, and so on.

Since pi is an irrational number, it has an infinite number of digits after the decimal point. Typically, for most uses, writing four or five digits after the decimal point suffice.  We can use the format() function to specify the number of digits that we want Python to print after the decimal point.

The syntax of the format function is

>>> a = format(x, ‘.nf’)

Where ‘n’ is the number of digits desired after the decimal.

And ‘x’ is the number to be printed.

How to Use format() Function

In the example below, we show how to use the format() function to print the value of pi to 3 decimal digits.

We make use of the math module (discussed in detail in the Python Modules chapter). The math module contains math functions such as trigonometric functions, logarithmic functions, angle conversion (degrees/radians), etc. Python math modules have 42 objects including two numbers “e” and “pi”. 

First, we import the math module. The mathematical constant pi (π) is available in the math module.

To get the value of pi, write the following statement.

math.pi

PROGRAM EXAMPLE: format() FUNCTION
>>> # Example of format() function
>>> # Import math module and use math.pi statement to get the value of pi.
>>> import math
>>> number = math.pi
>>> print(number)
3.141592653589793
>>> # Format() function to print the value of pi to 3 decimal place.
>>> format(number, '.3f')
'3.142'
>>>

Round() Function

Generally, we do not need high-precision numbers in the computation results. If a high-precision result in not required by the application, we round the computation result to the nearest tenth, hundredth, or thousandth, etc. For example, if the program involves money, we round the result to two decimal places (nearest cent).

Below are a few examples of how rounding is done,

If we want the result to be accurate to the tenth place, then 1.36 will be rounded to 1.4; and 1.33 will be rounded to 1.3.

Similarly, if we would like to report the result accurately to the nearest hundredth, then 1.234 will be rounded to 1.23; and 1.236 will be rounded to 1.24.

Python round() function rounds the floating point numbers as described below.

round(1.3) = 1

round(1.7)  = 2

round(-1.3) = -1

round(-1.7) = -2

The syntax of round() function is:

>>> round(x,n)

Where ‘x’ is the number to be rounded and ‘n’ is the number of digits desired after the decimal point.

How to Use round() Function

When you go shopping or buy books on Amazon, you pay the price of the book. In addition to the price of the book, you also pay an additional amount called sales tax.

Let us suppose the sales tax is 10%. If the book price is $100, you pay an additional $100 x 10% as sales tax. So the sales tax is $10. So, your total bill is ($100 + $10) = $110.  If the book is $50, you pay a sales tax of $50 x 10% = $5.  Therefore, the total amount you pay is ($50 + $5) = $55.

The following Python program shows how the sales tax is calculated and how the Amazon website will round the total bill to the nearest cent.

PROGRAM EXAMPLE: round() FUNCTION
>>> # Example of round() function
>>> # This program calculates sales tax on purchase price.
>>> Price = 29.99 # Price of the book
>>> sales_tax = 9.5/100 # Sales tax is 9.5%
>>> tax = Price * sales_tax
>>> print(tax)
2.84905
>>> total = Price + tax
>>> print(total)
32.83905
>>> round(total,2) # Round total bill to nearest cent.
32.84
>>> print('''The total bill rounded to nearest cent
is price + sales tax = ''', round(total,2))
The total bill rounded to nearest cent
is price + sales tax =  32.84
>>>

sum() Function

In the second-grade or third-grade math class, you have certainly gotten assignments to add two or more numbers. Adding numbers requires keeping track of the carry from the unit’s place to ten’s to hundred’s place etc.

Python’s sum() function can be used to find the sum of several numbers in a list. You create a list that has the numbers to be added. The sum() function adds up all the numbers in the list and returns the sum.

The arguments within the parenthesis of the list can be any numerical value or iterable (list or tuple). The iterable (list or tuple) must contain only numbers (no alphabets). The following example shows how the sum() function works.

PROGRAM EXAMPLE: sum() FUNCTION USE FOR LIST DATA TYPE
>>> Example for sum() function
>>> Define a list called ‘number_list’
>>> number_list = [ 1,2,3,4,5,6]
>>> sum(number_list)
21
>>> print('The sum of all numbers in the list = ', sum(number_list))
The sum of all numbers in the list =  21
>>> # Below is a more difficult addition problem
>>> numbers = [3495, 5619, 2873]
>>> addition = sum(numbers)
>>> print('The sum of 3495 + 5619 + 2873 = ', addition)
The sum of 3495 + 5619 + 2873 =  11987
>>> # or we can do the following
>>> print('The sum of 3495 + 5619 + 2873 = ', sum(numbers))
The sum of 3495 + 5619 + 2873 =  11987
>>>

The example below shows the sum() function operation for a tuple containing numerical values. It also shows that the sum() results on an empty tuple correctly gives a sum of 0.

PROGRAM EXAMPLE: sum() FUNCTION USE FOR tuple DATA TYPE
>>> # Example for sum() function for tuple data type
>>> # Define a sequence of numbers in a tuple ‘number_tuple’
>>> number_tuple = (1,2,3,4,5,6)
>>> sum(number_tuple)
21
>>> # Another way to add the numbers of a tuple
>>> sum((1,2,3,4,5,6))
21
>>> # Add an empty tuple
>>> sum(())
0
>>>

The above simple examples add numbers in a list or a tuple using the sum() function.

But how about using a for-range loop inside the parenthesis of the sum() function to create several computations in a single line of code? 

The program example below will perform the computations of the arithmetic expression x**2. It will evaluate it at each value of variable x specified in the for-range loop. It will then add the result of each computation.

PROGRAM EXAMPLE: sum() FUNCTION WITH for-range LOOP

>>> for-range loop within sum() function
>>> # the below line of code will sum the squares of all numbers from 3 to 5
>>> sum(x**2 for x in range(3,6))
50
>>>

fsum() Function

Python’s math module contains the function fsum().

If your list of numbers contains floating point numbers, it is preferable to use the fsum() function,

fsum() returns an accurate floating point sum of values. It avoids loss of precision by tracking intermediate partial sums.

The sum() function may not give an accurate result when adding floats due to rounding off at each intermediate addition step.  The example in the program below shows the lack of precision in adding floating point numbers using the sum() function. Notice the fsum() function gives an accurate answer when we add the number 0.1 ten times.

PROGRAM EXAMPLE: sum() FUNCTION AND fsum() FUNCTION USE
>>> #sum() function example Add a list that has number 0.1 ten times.
 >>> sum([0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1])
0.9999999999999999    # Note 1
>>> #fsum() function example.  Add a list that has number 0.1 ten times.
>>> import math
>>> math.fsum([0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1])
1.0    # Note 2
>>>

Note 1: sum() function loses precision when we add floating point numbers.

Note 2: fsum() function results in a precision answer.

Python max() and min() Functions

Suppose your school assignment is to find the largest number and the smallest from a list of 1000 numbers.

It would be very tedious, won’t it? Python has a built-in function called max() that returns the largest item in a string or list. The function min() will return the smallest item from the list.

max() and min() syntax:

max(expression , expression , …. )

max() returns the maximum of all the expressions listed within the parenthesis.

min(expression , expression , …. )

min() returns the minimum of all the expressions listed within the parenthesis.

max() and min() functions can be used for lists, tuples, strings, or dictionaries. They return the largest item for max() and the smallest item for min() functions respectively.

How Does max(), min() Functions Determine Maximum and Minimum Values For String Data Types

In the case of lists or strings, you might wonder how Python determines which character is bigger in a list of characters.

Python determines which character is bigger than another character as described below.

The computer stores the characters using what is called ASCII code, abbreviated from American Standard Code for Information Interchange. It is a character encoding standard for electronic communication.

ASCII codes represent text in computers by storing them as numbers. Each character and symbol is represented by a binary 8-bit code and a decimal equivalent number from 0 to 127. For example, the upper case ‘A’ has a decimal code of 65, and the lower case ‘a’ has a decimal code of 97. 

For strings, the max() function compares these ASCII code values to determine which character has a higher ASCII code. Min() function does just the opposite; it finds out which character in the string has the lowest ASCII code.

The list of ASCII code table for English characters and symbols is shown in Appendix.

The following program has two examples – one for a list consisting of integers, and the second for a string consisting of characters. The program finds the max and min of the list and string.

PROGRAM EXAMPLE: max() AND min() FUNCTION FOR NUMBER LIST AND STRINGS
>>> # Example for max() and min() function
>>> # Numbers list
>>> number_list = [1, 2, 3, 4, 5, 75]
>>> max(number_list)
75
>>> 
>>> min(number_list)
1
>>> max and min for strings
>>> character_string = 'aA'    # Note 1
>>> max(character_string)
'a'
>>> min(character_string)
'A'
>>>

Note 1: In the Appendix, ASCII code for character ‘a’.  It is 97. And the ASCII code of ‘A’ is 65. So, function max(aA) says ‘a’ is larger than ‘A’

max() and min() Functions for dict Data Type

Let us now use the max() and min() functions for the dict data type. The following program is an example of using the max() function for a dict data type and a list data type.

PROGRAM EXAMPLE: max() AND min() FUNCTION USAGE FOR dict AND list DATA TYPE
>>> # max() function usage for dict data type
>>> friends = {'alice' : '50', 'kathy' : '7.5', 'michael' : '8', 'steve' : '9', 'zhou' :'7'}
>>> max(friends)
'z'    # Note 1
>>> min(friends)
'alice'    # Note 2
>>>
>>> # max() and min() function for list data type.
>>> inner_planets = ['mercury','venus','earth','mars']
>>> max(inner_planets)
'venus'    # Note 3
>>> inner_planets = ['mercury','venus','earth','mars']
>>> min(inner_planets)
'earth'    # Note 4
>>>

Note 1: ‘z’ in ‘zhou’ has the highest ASCII code of all the friends’ names.

Note 2: ‘a’ in ‘alice’ has the smallest ASCII code.

Note 3: ‘v’ ASCII code in ‘venus’ is higher than all other planet names.

Note 4: ‘e’ ASCII code in ‘earth’ is smaller than all other planet names.

In the next chapter, we will apply all that we have learned so far to interesting math, physics, and geometry concepts.  You will see how what you have learned in school can be solved by writing simple Python programs. We will develop programs to create prime numbers, Fibonacci numbers, solve geometry problems, and more.

Copyright © 2019 – 2021 softwareprogramming4kids.com

All Rights Reserved

Verified by MonsterInsights