1.4. Expressions#

In Python, an expression is a combination of values, variables, operators, and function calls that can be evaluated to produce a result. Expressions are the building blocks of Python code, and they form the basis for performing computations, making decisions, and manipulating data. Here are some key points about expressions in Python [Downey, 2015, Python Software Foundation, 2024]:

Expressions in Python are combinations of values, variables, operators, and function calls that can be evaluated to produce a result. They are fundamental building blocks in Python that enable you to perform computations, make decisions, and manipulate data. Here are some key points about expressions:

1.4.1. Arithmetic Expressions#

Arithmetic expressions involve mathematical operations such as addition, subtraction, multiplication, division, and more. These expressions produce numeric results.

x = 5
y = 3
result = x + y * 2
print(result)  # Output: 11 (5 + 3 * 2)
11

In the example above, the multiplication is performed first due to operator precedence, resulting in 3 * 2 = 6. Then, the addition is performed: 5 + 6 = 11.

1.4.2. Comparison Expressions#

Comparison expressions compare values using operators like <, >, <=, >=, ==, and !=. These expressions result in boolean values (True or False).

Example:

a = 10
b = 7
is_greater = a > b
print(is_greater)  # Output: True
True

Here, the comparison operator > checks if a is greater than b, which is true, so the result is True.

1.4.3. Logical Expressions#

Logical expressions involve logical operations such as and, or, and not. They are used for making decisions and evaluating conditions, resulting in boolean values.

Example:

x = True
y = False
result = x and not y
print(result)  # Output: True (True and (not False))
True

The expression not y evaluates to True because y is False. Therefore, x and not y becomes True and True, which results in True.

1.4.4. String Expressions#

String expressions involve operations on strings, such as concatenation (joining strings) or accessing individual characters.

Example:

greeting = "Hello " + "Calgary!"
print(greeting)  # Output: Hello Calgary!
Hello Calgary!

The + operator concatenates the two strings, resulting in Hello Calgary!.

1.4.5. Function Call Expressions#

Function call expressions involve calling functions with arguments. The result of the function call is the value returned by the function.

Remark

In Section 1.11, we will discuss functions.

Example:

length = len("Python")
print(length)  # Output: 6 (length of the string "Python")
6

The len function returns the length of the string “Python”, which is 6.