0% found this document useful (0 votes)
5 views3 pages

Python Control Flow: If, Else, Elif

The lecture covers control flow in Python, focusing on the use of if, else, and elif statements to direct program execution based on conditions. It explains Boolean expressions, common mistakes, and nested conditions, emphasizing the importance of proper syntax and indentation. Homework includes a programming exercise to build a grade calculator and reading from the textbook.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views3 pages

Python Control Flow: If, Else, Elif

The lecture covers control flow in Python, focusing on the use of if, else, and elif statements to direct program execution based on conditions. It explains Boolean expressions, common mistakes, and nested conditions, emphasizing the importance of proper syntax and indentation. Homework includes a programming exercise to build a grade calculator and reading from the textbook.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

CS 101 – Introduction to Computer Science

Lecture 4: Control Flow – if, else, and elif


Date: October 2, 2024

Lecture Objectives:

• Understand conditional logic in Python

• Learn to use if, else, and elif statements

• Discuss Boolean expressions and truth tables

Key Concept: Control Flow

Control flow = directing the execution path of a program based on conditions

Basic if Statement:

x=5

if x > 0:

print("x is positive")

• The code inside the if block runs only if the condition is True

• Indentation is required (4 spaces is standard in Python)


else and elif:

x = -3
if x > 0:
print("Positive")
elif x == 0:
print("Zero")
else:
print("Negative")

• elif = “else if” → checks another condition

• else = catch-all if none of the above are True

Boolean Expressions:

• Python uses True and False (capitalized)

• Comparison operators:

• == (equal)

• != (not equal)

• > / < (greater/less than)

• >= / <=

age = 18
if age >= 18:
print("You can vote!")

Common Mistakes:

• Using = instead of == in conditions

• Forgetting the colon : at the end of if, elif, or else

• Misaligned indentation = IndentationError


Nested Conditions:

score = 92
if score >= 90:
if score > 95:
print("A+")
else:
print("A")

Nested if blocks allow more specific conditions inside broader ones.

Homework:

• Programming Exercise 2: Build a grade calculator

• Reading: Textbook Chapter 3 – Conditionals

• Optional: Practice problems on CodingBat

You might also like