Python Expressions

Tasks

  1. Complete reading this lesson, which involves the following:
    1. Structure of Python programs
    2. Arithmetic Expressions
    3. Logical expressions
    4. Rules of Precedence
    5. The math library

Introduction

In Lesson 2, you learned about basic components of a Python program like variables and literals. You also learned about the basic input and output statements, which enable you to receive data from the user and output the results to the console. Although these components are essential to any Python program, they are rarely used alone in writing Python code.

In this lesson, we integrate these basic components within more complex structures and write higher-level Python program segments, called expressions.

We start by acquiring some terminology that programmers use to refer to Python codes. You will learn about the terms: program, command, statement, expressions in addition to improving your understanding of the terms: variables and literals.

This lesson pays special attention to the concept of Python expressions. You will learn how to identify expressions in Python code. We also explore the different types of expressions and study several examples on how expressions are used and evaluated. The arithmetic expressions are inspected further, highlighting an important programming concept called rules of precedence. These rules govern how expressions are written and evaluated.

Finally, we introduce the concept of Python libraries. You will learn how to import the Python math library and use its build-in functions in your programs.

Program Components

When you look at any Python code, you see a sequence of lines written using the Python grammar rules, called Python syntax. These lines vary in length; some very short and others very long. We want to broadly analyze Python codes to identify what various portions of the code are. The emphasis here is on what is compared to what it means. This is analogous to looking at a piece of writing in the English language. Although you might not know the exact meaning of every word or phrase, yet you are able to identify characters, words, sentences and paragraphs. The way you identify these components is generic and not confined to a specific piece of writing. We want to build similar capacity when looking at any Python code.

Using an in-out perspective, the smallest components are called variables and literals. Next comes expressions, then statements and finally programs. Let us have a deeper look at these components.

The concept of variables was studied in depth in Lesson 2. You also came across the concept of a literal, but not in detail. These two concepts are revisited in this lesson for the purposes of understanding expressions.  

Variables

You have encountered the concept of variables in Lesson 2. We want to have a deeper look at this essential concept, not only in Python but for any programming language.

Think of a variable as some box in memory that has a tag or label name (identifier), contains some data and is associated with a type. For example, the command x = 5, allocates some memory location and attach to it the tag name of x. The value 5 is put inside that memory location, and we say that the variable x has a value of 5. The type of this variable is an integer, abbreviated in Python as int

The most distinguishing feature to remember about variables is that their value can 'vary', meaning you can change and update their value as you wish and at any time. This feature is different than a literal, which maintains a fixed form all the time. That means a variable can be resigned to reference another literal. For example, if we assign x=5 and y=x, then both x and y refer to literal 5. If later we assign y=10, then y refers to literal 10, x still refers to literal 5.

There are two interesting aspects about how Python deals with variables.

First, Python is a dynamically typed language. In simple terms, this means that Python allows you to change the type of the variable as you like, and it auto-detectthat change. For example, the variable x that we declared earlier is of type int, but you can change its type to a float when you write the command x = 5.0. This feature is not present in statically typed languages like C,C++ and Java. In these languages, if you declare x as an integer, then although the value can be changed, the type of the variable cannot be changed.

The second aspect of how Python deals with its variables is that it is a strongly typed language. In simple terms, if a variable is of a specific type and you need to deal with it as another type, then you need to explicitly do that through a process called casting, which was covered in Lesson 2. For example, the following is illegal in Python:

Illegal Code

x = 5
y = "hello"
x + y

Adding an integer variable to a string variable is illegal in Python:

Sample Execution
Traceback (most recent call last):
  File "test.py", line 3
    x + y
    ~~^~~
TypeError: unsupported operand type(s) for +: 'int' and 'str'

The strongly typed feature does not allow adding a variable of type int to a variable of type str. In a weakly typed language this would be allowed, and the interpreter would either auto-convert the integer to a string, or the string to an integer. An example of weakly typed languages including C and Visual Basic, while Java and Python are considered strongly typed.

The specifics of how Python is strongly and dynamically typed is beyond the scope of this course. However, the two aspects were highlighted in an attempt to avoid the common mistake of using data types without casting. Also, if you are coming from a C or Java background, recognizing that Python is a dynamically typed language is important to take advantage of the power of Python.

Literals

A literal is a fixed value located at some space in memory. This value is maintained the same all the time, and won't be changed in the program life time. For example, in the command x = 5, the left side is a variable, while the right side is a literal. The number 5 is a fixed value that resides somewhere in memory and this value does not change throughout the life cycle of the program execution. Python only holds one copy for each literal value in its life cycle. For example, if we further assign y = 5, then y refers the same literal of previous 5. In other words, both x and y refer to the same literal 5. When we further assign y = 6, then y refers to literal 6, x still refers to literal 5.

Take the following example:

Literal vs Variable

print('5')
print(x)

The first command prints the literal 5, and the output is the same regardless of where this command is located in the program. The second command prints the contents of the variable x, which varies depending on the value stored in the variable's memory at the time the print command is executed.

Just as variables have types, so do literals. For example, the literal 10 is of type int, the literal 'hello' is of type str, the literal 3.14 is of type float and the literal True is of type bool.

There is a special and interesting literal that is not associated with any type. This literal is None. If you assign None to a variable, then that variable contains that special value. There is only one None value defined by Python, and many variables can share it. Though not actually a string, when printed it displays the string None:

Using None

x = None
print(x)

Which produces:

Sample Execution
None

None is useful when you want to declare a variable but want to use it at a later time. It is similar to buying few boxes, filling some and keeping some empty for future use. In Python, when you want to keep the variable empty for future use, you assign it None. We will get back to this concept when we study lists.

Note that a literal is not a constant variable. Perhaps one of the best ways to conceptualize a constant variable is to think of a variable that resides in a box memory, but we decide to lock that box and disallow any further changes. In other words, a constant variable is changeable but we decide to freeze its value. As noted in Lesson 2, Python does not have a distinguished method for declaring variables as constants. However, as a convention, we use uppercase letters to name variables that we decide to treat as constants. (See: Constants)

In Python's terminology, we say if something can be changed then it is mutable, and if it cannot be changed then it is immutable. All primitive-type variables in Python, like integers, floats, booleans and strings are mutable. On the other hand, all literals are immutable.

Variables and literals are the inner most blocks of Python programs. Almost all meaningful Python programs contain a combination of variables and literals. Also all Python expressions are constructed using variables and literals.

Now that you properly understand variables and literals, we can move to the next building block of Python programs, called expressions.

Expressions

An expression is a segment of Python code that evaluates to some value. Or in other but similar terms, a segment of Python code that can be reduced to some value.

In computer science theory, there is a formal definition of expressions which we do not need to address in this course. The concept of an expression is better elaborated through a simple example. Let us inspect the following simple command:


x = 3 + 5

The left side is a variable x. The = character is an assignment operator. The right side 3 + 5 is an example of an expression. This expression is evaluated to some value, which here is the number 8. Or you could say this expression can be reduced to a value which is the number 8

Therefore, whenever we think of expressions we think of a piece of code that does a specific action, and only that action, which is evaluation. A segment of code that does not evaluate to some value is not an expression. For instance, the left side of any assignment statement is not an expression, while the right side is always an expression.  As another example, print and input commands are not expressions because they do not evaluate (or compute) something. Instead, they merely read or output to the console.  A third example, is the import statement, which is covered in a later section. The import statement links your program to an external library, and this command is not considered an expression.

Because of the observation that the right side of an assignment statement is always an expression, some programmers prefer to think of an expression as anything that can be put on the right side of an assignment statement. Many beginners find this an easy way to remember and identify expressions.

Expressions are your first step when you look for an unknown result. For instance, when you want to compute \(3^{100}\), then you need to write an arithmetic expression that can be evaluated to the result. Regardless whether you want to display the result to the console, save it in a file, or transfer it to a client/server on the internet, you must write an expression before doing any of that.

Expressions are integrated into many Python statements. This means that writing correct/proper expressions is a necessary condition for writing proper commands that produce the desired output. Many logical errors can be traced to writing incorrect expressions.

Expressions provides a higher level mechanism to describe most commands. For instance, we can describe an assignment statement as:


<var> = <expression>

We can describe an if statement as:


if <logical expression>

Therefore, if you understand what expressions are, it is easier for you to read manuals of programming languages which normally use higher level descriptions like the above. 

Statements

The third program component after variables/literals and expressions are statements. A Python statement is any line of code that performs some action. This action could be an assignment, a print, an input, an import, a branching, a loop, a call to a function or an evaluation of an expression.

The term command is a synonym to the term statement, and the programming community uses both terms interchangeably.

The easiest way to identify a statement in Python code is through code lines. Every line in Python code contains, and only contains, a single statement.

Simple vs. Compound Statements

Statements can be simple or compound.

A simple statement performs one action at a time. For instance: print(x) is a simple statement, because it performs the single action of printing the contents of the variable x to the console. Similarly, an assignment command, an import, or a return, or a function call are all simple statements.

Compound statements group several statements together within one block of code. Examples of compound statements include if, while and for statements. These could be easily identified through the indented blocks of code appearing at the same level. These statements will be studied in Lessons 5, 6, and 7.

Statements vs. Expressions

Statements are more general than expressions. Most statements compromise one or more expressions, but this is not a necessary condition. As discussed earlier, some statements do not contain expressions at all. Examples include the import, return and break statements. At the other end, some statements require an expression. An example of this category of statements is the assignment statement. Between these two ends, there are some statements that do not require expressions but may contain them. The print statement is an example, as you can write print(x) or print(x+5).

Statements Keywords

It is important to mention here that each statement has a unique reserved keyword (Remember this term from Lesson 2?) attached to it by the language syntax rules. For instance, the printing statement uses the keyword print, and the statement that receives data from the user uses the keyword input. This is true for the vast majority of statements. However, for some statements this could be tricky to identify. For example, the assignment statement uses the assignment operator =,and this operator is reserved for the assignment statement exclusively. In real life, the character = is used for both assignment and for equality check. But since each statement in Python requires a unique keyword, the character = is used for assignment and another operator is used for equality check which is the == operator. Confusing the = and == operators is a common mistake for those learning Python. Keep your eye out for it.

Statement Types

There are many types and forms of Python statements. Very few programmers know all of them. Most programmers learn the basic statements and refer to the Python documentation if they need help with other statements. This is the approach followed in this course. It is not about teaching you everything in Python, but about equipping you with the basic tools and the capacity to continue learning when the course is over.

Program

The highest level of Python code is a program. A program is a collection of variables, literals, expressions and statements grouped together to achieve a specific goal. In other words, the various program components are connected together to achieve the desired program objectives.

Although it is possible to have a program with a single statement, most programs consist of many statements. These statements can be organized in various methods. For the purposes of this course, statements that appear in a Python program normally fall in one of the following four categories:

Sequential Statements
These statements are executed line by line based on how they are ordered in the Python program. None of these statements get jumped over or skipped. The assignment, print and input statements are examples of statements under this category.
Conditional Statements
are statements that evaluate logical expressions, and are based on the result of executing other statements. If the logical expression is evaluated as True, some block of code gets executed. This block does not get executed if the expression False, so access to the block is conditional. The if-else statement is an example of a conditional statement. You will learn about conditional statements in Lesson 5.
Iterative Statements
are statements that allow a specific block of code to repeat several times. The number of iterations can be a fixed number or indefinite until a specific exit condition is satisfied. Example of these statements are the for and while statements. You will learn about these in Lessons 6 and 7.
Functions
are blocks of code that get executed when the user decides to do that through a special statement called a function call. Unlike a conditional statement, the execution of the function block is not based on satisfying a specific condition. Instead, it is based on the developer's choice. You will learn about functions in Lesson 4. Functions can be considered little programs, and thus can contain a combination of sequential, conditional and iterative statements. However, these 'little programs' do not exist by themselves and appear within the code of a bigger program that act as the coordinator between various program components. This is referred to as the main program.

Summary of Program Components

To summarize this section, we say a Python program consists of a group of statements or commands. Each statement is a line of code that does something. Most statements include expressions. An expression is a code segment that evaluates to some value. The main building blocks of an expression are variables and literals. Statements within a program could be organized sequentially, conditionally, iteratively or using smaller modular blocks called functions.

You might find the information presented in this section mainly theoretical. However, it will equip you with better clarity while you are coding. It also organizes your thought process of how you read and write Python code. In the following sections, attention is shifted to the practical side where you will learn how to write Python expressions.

Expressions

Components of a Python Expression

You have already learned that an expression evaluates to a value. Now, it is time to learn what it consists of, and how it is organized/structured.

Every Python expression consists of one or more of the following:

The above three components could be organized in various forms. The most common form is the following:


<variable or literal> <operator>  <variable or literal>

Below is an example of an expression of the above form:

However, the above common form is not exclusive and expressions can appear in several other forms. Study the following example:

As you notice, expressions can take various forms. Nevertheless, we can say that every expression contains at least one literal or variable and at least one operator.

Basics of Expression Writing

The process of writing any Python expression can be captured in four main steps:

  1. Selecting the expression type
  2. Selecting variables and literals
  3. Selecting operators
  4. Applying rules of precedence to organize the expression

Step 1: Selecting the Expression Type

Whenever you recognize that you need to use an expression in your program, this means there is something that you need to evaluate. The result could either be known to you (intuitively or through some little work), or unknown to you (or would require substantial work to find out). In both cases, you should have an idea about the data type of the expected result. This will be the basis for selecting the right expression type.

Although there are several expression types in Python, the four types of most interest to this course are:

arithmetic expressions
An arithmetic expression is an expression that evaluates to a number, generally either int or float.
logical expressions
A logical expression evaluates to bool value of True or False. Another way to think of logical expressions is if it provides an answer to a question in the form of Yes or No.
string manipulation expressions
String manipulation expressions are those that involve some operations on strings, normally resulting in a modified version of the data.
list manipulation expressions
List manipulation expressions are those that involve some operations on lists, normally resulting in a modified version of the data.

Your focus should be on the type of the output/result, not the type of the variables used.

For instance, assume that you have the following variables:


x = 3
y = "4"

The variable x is of type int, and the variable y is of type str.

If you want to print to the console the result of adding the number 3 to the number 4, which is a number, then you need to construct the following arithmetic expression in the print statement:


print(x + int(y))

Notice how casting the string variable y was necessary to produce the desired output. On the other hand, if you are looking to repeat the string "4" as many as 3 times, which results in an output of type string, then you need to construct a string manipulation expression similar to the following:


print(y * x)

In string expressions, the star operator (*) duplicates the first operand as many as the number provided in the second operand.

As you can see, the type of the result was the primary factor in choosing the expression type, not the type of the operands.

Step 2: Selecting Variables and Literals

Once you have selected the expression type, the next step is to select which variables and literals you want to choose. These variables/literals are the operands of the operator selected in the next step.

This step is mainly a design step that can be achieved in various ways depending on the desired output and available variables. Part of this step requires precision in selecting the correct variables, and the other part is a design choice that has no definitive right or wrong choice. Let us elaborate this through an example.

Assume you have the following variables:


circle1_r = 2.5
circle2_r = 7.1
PI_LONG = 3.141592653
PI_SHORT = 3.14

Let the objective of your expression be to compute the area of the first circle and store the result in the variable area1. Using the first step, we know that an arithmetic expression should be used. In the second step, we can easily see that we need to use the variable circle1_r, because using the variable circle2_r would result in a logical error. For selecting the value of the mathematical constant \(\pi\), we have multiple options like:

  1. Using the variable PI_LONG
  2. Using the variable PI_SHORT
  3. Using the literal 3.14
  4. Using the literal 3.141592653

Selecting any of the above constructs the correct expression. However, if you are looking for higher precision, then option (1) and (4) are preferred. Also, using constants is considered a better programming practice than using literals, which gives preference to options (1) and (2). Based on this, option (1) seems the best design choice, but the other three options are still valid options.

Step 3: Selecting Operators

After determining the expression type and selecting the variables and literals, selecting the right operator is narrowed down to one or few options from the long list of Python operators. Below are few considerations to take into account when selecting the operator:

  1. Would the use of the selected operator produce a logically correct answer?
  2. Is it legal to use the operator for the given variables/literals? If it is illegal, can I make it legal by casting one or both operands?
  3. Does the selected operator provide the simplest form of the expression?
  4. Does the selected operator provide better readability of the expression?

The correct expression is:


area1 = PI_LONG * circle1_r ** 2

Using the multiplication (*) operator twice in place of the exponentiation operator (**) is a legal choice for the above expression, which could be written as:


area1 = PI_LONG * circle1_r * circle1_r

However, using the (**) operator is probably simpler and provides better readability.

Step 4: Applying Rules of Precedence

Rules of precedence refer to policies followed by Python to determine which operator in the expression should be evaluated first. For instance, to write an expression that computes \(\frac{3+5}{2}\) we should use the expression:


(3+5)/2

Not


3+5/2 or 3+(5/2)

Based on the Python rules of precedence, the division operator (/) has higher precedence over the addition operator (+), which results in evaluating the expression as: \(3+\frac{5}{2}\) , which is logically incorrect. We revisit in more detail Python's rules of precedence later.

We have provided a lengthy explanation of how to write Python expressions because it is one of the main areas that can cause logical errors in a program. The above four steps are helpful when writing complex expressions. For simple expressions, the above steps appear hand-in-hand and writing the expression is normally intuitive. Also, as you become more skilled in Python writing expressions will be a second nature to you, and you won't have to spend much time thinking about them.

Operators

Python has a rich and amazing list of operators that can be used in writing expressions. An operator is a symbol selected by Python to do a specific action. Operators can perform operations using two operands or a single operand. We call operators that apply to a single operand: unary operators.

This section has a list of Python operators focusing on those relevant to this course. To provide easier reference, the operators are presented in categories and organized in a tabular format:

Python Arithmetic Operators
Symbol Operator Example
+ Addition 3 + 5
- Subtraction, or
Unary Minus
5 – 3
-5
* Multiplication 5 * 3
/ Division 3 / 5
// Integer Division 17 // 5
% Modulus (Remainder) 17 % 3
** Power (Exponentiation) 4 ** 2
Python Boolean Operators
Symbol Description Example
and Returns True only if both operands are True
Returns False otherwise
True and False : False
or Returns True if either operand is True
Returns False if both operands are False
True or False : True
not Unary negation operator
Returns True if operand is False or None
Returns False if operand is True
not True : False
Python Comparison Operators
Symbol Description Example
== Check if operands are equal 3 == 5 : False
> Check if first operand is greater than second operand 3 > 5 : False
>= Check if first operand is greater than or equal to second operand 5 >= 5 : True
< Check if first operand is smaller than second operand 3 < 5 : True
<= Check if first operand is smaller than or equal to second operand 3 <= 5 : True
!= Check if operands are not equal 3 != 5 : True
Python Assignment Operators
Symbol Description Example -> Equivalent
= Assigns the variable on the left the value of evaluating the expression on the right x = 10
+= Addition then assignment x += 3 -> x = x + 3
-= Subtraction then assignment x -= 3 -> x = x – 3
*= Multiplication then assignment x *= 3 -> x = x * 3
/= Division then assignment x /= 3 -> x = x / 3
//= Integer division then assignment x //= 3 -> x = x // 3
%= modulus then assignment x %= 3 -> x = x % 3
**= power then assignment x **= 3 -> x = x ** 3
Python Membership Operators
Symbol Description Example
in Returns True if first operand is part of the second operand 3 in [1,2,3,4] : True
not in Returns True if first operand is not part of the second operand 7 not in [1,2,3] : True
Python Identity Operators
Symbol Description Example
is Returns True if first operand is the same as the second operand x is x : True
is not Returns True if first operand is not the same as the second operand x is not y : True
Note: often used with None, although we won't see much of that before CP164

In addition to the above, some of the operators could be used with lists and strings.

Python List and String Operators
Symbol Description Example
+ Joins two lists
Concatenates two strings
[1,2] + [3,4] : [1,2,3,4]
'AB' + 'CD' : 'ABCD'
* Duplicate [1,2] * 2 : [1,2,1,2]
'AB' * 3 : 'ABABAB'

There are additional list and string operators like the access and slicing operators. These are introduced in Lessons 8 on Lists and Lesson 9 on Strings.

Precedence

Rules of precedence are used by Python to evaluate terms within an expression. General rules apply regardless of the type of expression. Specialized rules apply to other, specific, expressions.

Rule 1: Assignment operators have the least precedence among all operators

The contents of the right side of an assignment operator (=) are always evaluated before assigning the evaluation result to the variable on the left side of the operator.

Another example:

Rule 2: Terms bounded within parentheses ()are evaluated first

This rule suggests that any part of the expression that exists within the parentheses ( ) gets evaluated first. In other words, the ( ) operators have higher precedence over all other operators.

Rule 3: Evaluate equal precedence operators from left to right

When the same operator is used multiple times in an expression, or when operators of equal precedence appear consecutively within an expression, the expression is evaluated from left to right.

Rules of Precedence for Arithmetic Expressions

The following table shows the rules of precedence for arithmetic operators, ordered from highest to lowest:

Rules of Precedence
Symbol Description
** The power operator has the highest precedence among all arithmetic operators
+
-
The unary plus and minus operators are of equal precedence.
These two operators have the highest precedence among arithmetic operators, except the power operator
*
/
//
%
The multiplication, division, integer division and modulus operators are of equal precedence and have higher precedence over addition and subtraction operators
+
-
The addition and subtraction operators are of equal precedence and have the lowest precedence.

Below is an example of applying the above rules:

Rules of Precedence for Logical Expressions

The following table shows the rules of precedence for logical operators. Since comparison operators also return a value of True and False, we have merged them in the same table along with the logical operators:

Rules of Precedence for Logical Expressions
Symbol Description
==
!=
>
>=
<
<=
Comparison operators have higher precedence than logical operators

The six comparison operators have equal precedence
not The Boolean NOT operator has the highest precedence among logical operators
and The Boolean AND operator has higher precedence than the Boolean OR operator
or The Boolean OR operator has lowest precedence among logical operators

Here is an example that applies the above rules:

Summary of Rules of Precedence

It is common in Python to have expressions that are of mixed operator types. For instance, in Example 3.4.F, the expression contained both comparison and logical operators. Therefore, it is important to have a holistic overview of operator precedence in Python. The following table, provides a summary of the rules, ordered from highest to lowest precedence.

Symbol Description
( ) Expressions within () get evaluated before any other expressions
** The power operator
+
-
The unary plus and minus operators
*
/
//
%
The multiplication, division, integer division and modulus operators
+
-
The addition and subtraction operators
==
!=
>
>=
<
<=
in
not in
is
is not
Comparison, membership and identity operators
not The Boolean NOT operator has the highest precedence among logical operators
and The Boolean AND operator has higher precedence than the Boolean OR operator
or The Boolean OR operator has lowest precedence among logical operators
=
+=
-=
*=
/=
//=
%=
**=
Assignment operators

Python Libraries

When you install Python in your machine, a set of Python files that store Python commands are copied to your machine. These files are called Python Libraries. As the term library suggests, it contains a collection of functions (analogous to books). Each of these functions provide a programming tool that you can use when writing your programs.

Python Standard Library

The most important library is the Python Standard Library. This library defines the basic and most frequently used Python commands that developers use in their coding. For example, the definitions of the print and input functions are found at the Standard Library. The following table shows some of the built-in Python functions found in the standard library:

Python Standard Library Functions
Function Description
abs(n) Returns the absolute value of the number n
bin(n) Returns the binary version of the number n
chr(c) Returns the corresponding character of the Unicode character c
format(string) Formats values defined in a format string
hex(n) Returns a hexadecimal value of the number n
input(prompt) Prints a prompt and returns a user input
isinstance(object) Checks if object is of a specific type
iter() Returns an iterator object
max(…) Returns the maximum item in an iterable object
min(…) Returns the minimum item in an iterable object
print(…) Prints a given value to the console
range() Returns a sequence of numbers starting from 0 up to a given value
round() Rounds a number
str() Returns a string representation of an object

The standard library is automatically loaded when you launch the Python Interpreter. You can code directly without any extra work.

Importing Python Libraries

The import command loads the specified library and allows you to use it henceforth in your program. In the next subsection, we will explain how to use the import command.

There are a number of ways to import libraries in Python, but there is one approach we require in CP104 and CP164. To use the functions of a library you must put the statement:

from library import function or constant[, function or constant]

at the beginning of your code. This import statement gives your Python programs access to all of the listed functions and constants of the library. To use a function from an imported library, you must name the function when importing the library. If you attempt to use a library function or constant without importing the library:

No Import
        
value = sqrt(pi)

      

the following error occurs:

No Import Error
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'sqrt' is not defined

To work properly, the sqrt function (and the pi constant) must be imported from the math library:

Good Import
        
# Imports
from math import sqrt, pi
…
value = sqrt(pi)
…

      

Python Math Library

You might have noticed when looking at Table 1 that the Python Standard Library supports some mathematical functions. An example of this is the abs() function, which computes the absolute value. Another example is round(), which rounds any given number to the nearest whole number based on some defined precision.

However, the scope and application of these functions is limited and does not allow for making computations that could be done in a standard calculator. Basic functions like square root, logarithmic functions and trigonometric functions are absent. These functions are found in the math library. The math library also includes selected constants.

The following table provides a summary of some functions and constants found at the Python math library. The full list can be found in this Python documentation link.

math Library Functions
Function / Constant Description
ceil(x) Returns the ceiling of x, i.e. the smallest integer greater than or equal to x
fabs(x) Returns the absolute value of a the float variable x
factorial(x) Returns x!
floor(x) Returns the floor of x, i.e. the smallest integer less than or equal to x
gcd(a, b) Returns the greatest common divisor of a and b
exp(x) Return e raised to power of x
log(x) Returns the natural logarithm of x (base e)
log10(x) Returns the base-10 logarithm of x
pow(x,y) Returns x raise to the power y
sqrt(x) Returns square root of x
cos(x) Returns the cosine of x radians
sin(x) Returns the sine of x radians
tan(x) Returns the tangent of x radians
degrees(x) Converts angle x from radians to degrees
radians(x) Converts angle x from degrees to radians
pi A predefined value of pi
e A predefined value of e (Euler's Number)

To put everything taught in this lesson into practice, we work with examples that involve writing expressions and using functions from the math library. Check the next section.

Other Python Libraries

Python offers many more tools and specialized functions than those defined in the Standard Library. The following table show examples of these libraries:

Examples of Other Python libraries
Library Description
random Contains functions for random number generation
datetime Enables processing of date and time objects
re RegEx library enables working with regular expressions used mainly for pattern searching
requests Provides tools for http requests using Python

Some of the above libraries are installed along with the installation of Python, while others require independent installation. If the module is installed in your machine and you need to use it, then you need to inform the Python interpreter about that. This is done through the import command.

Examples

Conclusion

In Lesson 3, you have learned about the components of a Python program. You can now identify variables, literals, expressions and statements. You have built the competency to write simple arithmetic expressions and apply rules of precedence. You have also learned how to import a Python library and use it in your code. Specifically, you are now familiar with the math library and its functions and constants.

In the next week, you will be introduced to another important problem solving skill in programming called functions. You will learn how to break your program into smaller portions which can be reused in different parts of your code.

Check Weekly Schedule for Assessments

References

  1. Peter Wentworth, Jeffrey Elkner, Allen B. Downey and Chris Meyers. (October 2012). How to think like a Computer Scientist. Learning with Python 3: Chapter 2: Variables, expressions and statements.Open Book Project. ACM50, 1 Retrieved on July 15, 20
  2. Python Software Foundation (No date). Python Standard Library. Retrieved on July 29, 2020. 
  3. Python Software Foundation (No date). Python math Library. Retrieved on July 29, 2020.