03. Expressions and Boolean Logic
A progressive guide to Python expressions, arithmetic and comparison operators, Boolean logic, strings, evaluation order, and common expression errors.
1. Building Blocks of Expressions
An is code that produces a value when it is evaluated. Expressions can contain literals, variables, operators, and function calls. For example, 3 + 4 produces 7, length * width produces a product, and age >= 18 produces True or False.
An performs an operation, and an is a value acted on by an . In a + b, + is the while a and b are the operands. Small expressions can be combined into larger expressions.
The key distinction is between producing a value and assigning a value. The x == 10 asks whether x equals 10, while x = 10 assigns 10 to x.
Takeaway: An produces a value; operators describe the operation, and operands provide the values being operated on.
2. Arithmetic Expressions
Arithmetic expressions calculate numeric values. Common Python arithmetic operators include:
+for addition, such as7 + 3, which produces10.-for subtraction, such as7 - 3, which produces4.*for multiplication, such as7 * 3, which produces21./for division, such as7 / 2, which produces3.5.//for floor division, such as7 // 2, which produces3.%for the remainder, such as7 % 2, which produces1.**for exponentiation, such as2 ** 3, which produces8.
A unary acts on one . For example, -5 represents negative five, and +number represents the positive form of number.
Parentheses make grouping explicit. In result = (total - discount) * tax_rate, the subtraction is performed before multiplication because the parentheses require that grouping.
Takeaway: Use arithmetic operators for numeric calculations, and use parentheses when the intended grouping should be immediately clear.
3. Comparing Values
A compares values and normally produces a Boolean value: True or False. Python comparison operators include == for equality, != for inequality, < for less than, > for greater than, <= for less than or equal to, and >= for greater than or equal to.
Do not confuse assignment with equality. The statement x = 10 stores a value in x, whereas x == 10 tests whether the current value of x is equal to 10.
Comparisons can be chained. The 10 <= score <= 20 means that score is at least 10 and at most 20; in Python, it is equivalent in meaning to 10 <= score and score <= 20.
The operators <, >, <=, and >= can also compare strings lexicographically, according to character ordering. String comparisons are case-sensitive, so uppercase and lowercase characters may compare differently. For example, "apple" < "banana" is True, and "A" < "a" is True in Unicode code-point ordering.
Takeaway: Comparisons answer questions about values, while assignment changes a variable's stored value.
4. Boolean Logic and
Logical operators combine or modify conditions. not reverses a truth value, and is true when both conditions are true, and or is true when at least one condition is true. For example, (age >= 18) and has_id checks two requirements, while is_member or has_coupon accepts either condition.
allows values to be interpreted as true or false in a Boolean context. In Python, False, None, numeric zero, and empty strings and containers are false; most other values are true. Thus, if not name: can detect an empty string stored in name.
determines whether later operands need to be evaluated. A and B stops when A is false because the complete result cannot be true. A or B stops when A is true because the complete result is already true.
For example, is_valid and submit_form() calls submit_form() only when is_valid is true. Similarly, number != 0 and 100 / number > 2 avoids attempting the division when number is zero. Python's and and or return one of their operands rather than always returning a Boolean. This supports patterns such as username = entered_name or "Guest", which produces "Guest" when entered_name is empty.
Takeaway: Logical expressions combine conditions, and short-circuiting can both improve efficiency and prevent unsafe operations.
5. Working with Strings
String expressions construct, combine, compare, and inspect text. joins strings with +. For example, first + " " + last combines a first name, a space, and a last name. Both operands must be strings in this form, so a number must be converted with str before it is concatenated.
The * repeats a string. For example, "-" * 5 produces "-----". The in and not in operators test string membership: "cat" in "concatenate" is True, while "dog" not in "concatenate" is also True.
A inserts results into text. In f"{name} scored {score}%", the expressions inside the braces are evaluated before the final string is produced. Formatted strings are often clearer than manually concatenating text with converted numbers.
Takeaway: Strings can be joined, repeated, searched, compared, and created from evaluated expressions.
6. Grouping and Order
determines which operations are grouped first. A simplified Python order from highest to lowest is:
Parentheses, indexing, function calls, and attribute access.
Exponentiation, such as
**.Unary operators, such as
+x,-x, andnot x.Multiplication, division, floor division, and remainder:
*,/,//, and%.Addition and subtraction:
+and-.Comparisons, membership tests, and related operators.
Boolean
not.Boolean
and.Boolean
or.
For example, 2 + 3 * 4 is grouped as 2 + (3 * 4) and produces 14. Parentheses change the result: (2 + 3) * 4 produces 20.
determines grouping when operators share a precedence level. Most arithmetic operators group from left to right, so 20 / 5 * 2 is grouped as (20 / 5) * 2 and produces 8. Exponentiation groups from right to left, so 2 ** 3 ** 2 is grouped as 2 ** (3 ** 2) and produces 512.
To perform reliably, identify the innermost parentheses, apply operators according to precedence, follow , apply short-circuit rules, and then determine the final value and type. Parentheses are especially useful when an could be misunderstood.
Takeaway: Precedence and control grouping; parentheses communicate intent and reduce mistakes.
7. Avoiding Common Errors
Several common errors arise when expressions combine different kinds of operations.
Use
=for assignment and==for comparison. A condition such asif score == 100:tests equality.Do not rely on remembered precedence when clarity matters. Write
(score >= 50) and (attendance >= 0.8)when both requirements must be satisfied.Do not directly concatenate a string and an integer, as in
"Count: " + 3. Convert the number or use a such asf"Count: {3}".Make logical requirements explicit. For example,
(age >= 18) and has_permissionclearly expresses that both adulthood and permission are required.
When analyzing an unfamiliar , first identify its values and operators, then inspect parentheses and precedence. Next check whether comparisons produce the expected conditions, whether affects a Boolean context, and whether short-circuiting prevents any later from running.
Final takeaway: Correct reasoning depends on distinguishing assignment from comparison, grouping operations deliberately, matching compatible types, and tracing Boolean step by step.