Booleans and Conditional Statements - Comprehensive Notes
- You’ll see this used very often: you can select lines to temporarily disable them without deleting
- Mac: Command + /; Windows: Ctrl + /
- What it does: comments out every line in the selected block
- This is useful when you’re experimenting or changing code but want to keep the old version for reference
- Example in lecture: after highlighting lines, press the shortcut to comment, then write a new version to compare
- You can toggle comments with the same shortcut (comment/uncomment)
- This concept is simply called “comments” in code
Booleans: a new data type in Python
- Booleans (bool) are a new data type in Python
- Previously discussed data types: Integers, Floats, and Strings
- Booleans have only two possible values: true/false in everyday language, but in Python the literals are capitalized: True and False (keywords in Python)
- Lowercase true/false are not standard boolean literals in Python; they are treated as names if defined by the user, otherwise they’re not booleans
- Note on null: the transcript mentions null as a concept but we won’t cover it here; focus is on True/False
- Booleans can be assigned like other data types, e.g.,
flag = True or flag = False
Boolean expressions
- A Boolean expression is an expression that evaluates to a Boolean value: True or False
- Think of Boolean expressions as yes/no questions or statements that evaluate to True or False
- Examples:
- It is raining outside → can be either True or False
- The expression
10 > 5 → True, because 10 is greater than 5 - A string comparison example: comparing two strings using relational operators will yield a Boolean result
- Boolean expressions are often built using relational operators (see below)
Relational operators and equality
- Relational operators (operators that compare values) include:
- Greater than: ">"
- Less than: "<"
- Greater than or equal to: ">="
- Less than or equal to: "<="
- Equal to: "==" (note: this is the equality test in Python)
- Not equal to: "!="
- In Python, there is an important distinction between the assignment operator and the equality operator:
- Assignment operator:
= (used to assign a value to a variable) - Equality operator:
== (used to compare two values and produce a Boolean result) - The analogy the lecture uses: assignment is a statement (it assigns), while
== is a question (are these two values equal?)
- Practical note:
- When you write a condition, you’ll commonly use these relational operators to form a Boolean expression, which can then drive conditional statements
Strings and ASCII-based comparisons
- Python can compare strings using relational operators because each character has an ASCII value
- How it works: compare strings left to right, character by character, using their ASCII codes until a difference is found
- Example: compare
'code' and 'coat' (all lowercase)- Characters:
'c' vs 'c' → both 99, so equal'o' vs 'o' → both 111, so equal'd' vs 'a' → 100 vs 97; since 100 > 97, 'code' > 'coat'- ASCII values to recall:
'c' = 99, 'o' = 111, 'd' = 100, 'a' = 97
- Important caveat: string comparisons depend on case; all-lowercase or all-uppercase strings compare lexicographically within the same case
- Lexicographic order (alphabetization) can be used to sort strings, assuming consistent case across all strings being compared
- This concept is often used in homework and programs to order words or lists of strings
Why Boolean expressions matter
- Boolean expressions are used to control the flow of a program via conditional statements
- They enable programs to perform actions only when certain conditions are met
- The next topic shows how to build sequences of conditions using three clause types: if, elif, and else
Conditional statements (if, elif, else)
- Conditional statements check whether a Boolean expression is true and execute code accordingly
- There are three kinds of clauses you can use, in combination:
- if clause (required, and must be the first clause)
- elif clause (optional, can have zero or more; used for additional conditions)
- else clause (optional, handles the default case when none of the previous conditions are true)
- Indentation is critical in Python: the block of code that runs if a condition is true must be indented under the corresponding clause
- Conceptual intuition: an if clause is like asking a question; if True, do something; if False, do nothing (or wait for other branches)
If clause
- Structure of an if clause in Python:
if <Boolean_Expression>:- (newline, indented) code to execute if the expression is True
- Examples and explanations from the lecture:
- Example 1:
if 10 > 5: followed by an indented block, e.g., print("10 is greater than 5") → executes because the expression is True - Example 2:
if my_age > your_age: with appropriate values; if True, prints a message; if False, nothing happens in that branch - Example 3:
if my_num == your_num: then print("Great minds think alike") → True if numbers are equal - Example 4:
if my_num != your_num: → executes only when the numbers are not equal
- Notes in the lecture about equality and inequality:
== checks for equality; != checks for inequality- The lecture also mentions a hypothetical about a not-equal case and “not equal to” logic
Elif clause
- Elif (else-if) clauses provide additional conditions to check after the initial if
- You can have zero or more elif clauses; they are optional
- Important rules:
- An elif clause must come after at least one if clause
- The syntax is similar to the if clause:
elif <Boolean_Expression>: followed by an indented action block
- Conceptual example (traffic light):
- If the light is red, stop
- Elif the light is yellow, slow down
- Elif the light is green, go
- Else (if none of the above), handle a default case (e.g., broken light)
- In practice, you can chain multiple elifs, for example:
if condition1: ... elif condition2: ... elif condition3: ...
Else clause
- Else clause provides a default action when none of the previous conditions are true
- Structure:
else: followed by an indented block of code - Use case: catch-all when no earlier condition matches
- Note: Else is optional and should come after all if/elif blocks
Indentation and syntax essentials in Python
- Indentation determines blocks of code (no braces like in some other languages)
- The code in the if/elif/else blocks must be indented consistently (e.g., one tab or a consistent number of spaces)
- Mis-indentation leads to syntax errors and can break program execution
- The lecture shows examples where lines within the condition’s block are indented one level; the condition line itself is at the outer level
Real-world analogy: traffic lights
- Approach to a traffic light illustrates a chain of conditional checks:
- Is the light red? If True, stop
- Else, is the light yellow? If True, slow down
- Else, is the light green? If True, proceed
- At most one condition is true at a time, guiding the action
- This maps directly to Python’s if/elif/else flow control
Practical notes and next steps
- You’ve seen how boolean values, boolean expressions, and relational operators come together to form conditional logic
- In upcoming work, you’ll apply these concepts to real programs and homework (including string ordering and conditional decision-making)
- Practically, this is foundational for control flow in almost all Python programs
- Ethical or philosophical implications are not discussed in this section; the focus is on programming syntax and logical reasoning
Quick reference: key symbols and terms
- Boolean values: True, False (capital T/F)
- Booleans in code: used to represent truth values
- Assignment vs equality:
- Assignment:
= - Equality:
==
- Relational operators:
>, <, >=, <=, ==, != - String comparison relies on ASCII values and lexicographic order; example sequence involves character-by-character comparison
- Indentation is essential in Python blocks under if/elif/else
- Commenting shortcut: Mac: Command +
/, Windows: Ctrl + /
Examples to try (summary you can reproduce in Python)
- If example 1:
- if 10 > 5:
- print("10 is greater than 5")
- If example 2 (age):
- my_age = 28
- your_age = 19
- if myage > yourage:
- print("I am older")
- If example 3 (equality):
- a = 7; b = 7
- if a == b:
- print("Great minds think alike")
- If example 4 (not equal):
- if a != b:
- print("They are different")
- Elif example:
- age = 20
- if age < 13:
- print("child")
- elif age < 20:
- print("teenager")
- else:
- print("adult")
- String comparison example:
- s1 = 'code'
- s2 = 'coat'
- if s1 > s2:
- print("'code' is greater than 'coat'")