Python for Beginners - Part 2: Control Flow - Making Decisions and Loops
Welcome back to our Python coding course! In Part 1, we covered the basics of Python syntax, variables, and data types. Now, in Part 2, we'll explore Control Flow, which allows your programs to make decisions and repeat actions. This is where your code truly becomes dynamic!
Conditional Statements: if, elif, else
Conditional statements allow your program to execute different blocks of code based on whether certain conditions are True or False.
The if statement:
The simplest form. The code block inside if runs only if the condition is True.
temperature = 25
if temperature > 20:
print("It's a warm day!")
The else statement:
Used with if to provide an alternative block of code to run if the if condition is False.
age = 17
if age >= 18:
print("You are an adult.")
else:
print("You are a minor.")
The elif (else if) statement:
Used for checking multiple conditions sequentially. Python checks if first, then elifs in order, and finally else if none of the above are true.
score = 85
if score >= 90:
print("Grade: A")
elif score >= 80:
print("Grade: B")
elif score >= 70:
print("Grade: C")
else:
print("Grade: F")
Important: Python uses indentation (whitespace at the beginning of a line) to define code blocks. A consistent indentation (usually 4 spaces) is crucial!
Comparison Operators
These operators are used to compare two values and return a Boolean result (True or False).
| Operator | Description | Example | Result |
| Equal to |
|
|
| Not equal to |
|
|
| Greater than |
|
|
| Less than |
|
|
| Greater than or equal to |
|
|
| Less than or equal to |
|
|
x = 10
y = 5
print(f"Is x equal to y? {x == y}")
print(f"Is x not equal to y? {x != y}")
print(f"Is x greater than y? {x > y}")
Logical Operators: and, or, not
These operators combine conditional statements.
and: ReturnsTrueif both conditions areTrue.or: ReturnsTrueif at least one condition isTrue.not: Reverses the Boolean result of the condition.
has_license = True
has_car = False
is_rainy = True
if has_license and has_car:
print("Ready to drive!")
else:
print("Cannot drive without both a license and a car.")
if has_license or has_car:
print("You have at least one of these.")
if not is_rainy:
print("It's not raining, enjoy the outdoors!")
Loops: Repeating Actions
Loops allow you to execute a block of code multiple times. Python primarily has two types of loops: for and while.
The for Loop
The for loop is used for iterating over a sequence (like a list, tuple, dictionary, set, or string) or other iterable objects.
# Looping through a list of fruits
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
# Looping through a range of numbers
# range(5) generates numbers from 0 up to (but not including) 5: 0, 1, 2, 3, 4
for i in range(5):
print(f"Number: {i}")
# Looping with start and end (range(start, end))
for i in range(2, 7): # Numbers from 2 up to (but not including) 7: 2, 3, 4, 5, 6
print(f"Counting: {i}")
# Looping with start, end, and step (range(start, end, step))
for i in range(0, 10, 2): # Numbers from 0 up to 10, incrementing by 2: 0, 2, 4, 6, 8
print(f"Even number: {i}")
The while Loop
The while loop continues to execute a block of code as long as a condition is True. You must ensure that the condition eventually becomes False to avoid an infinite loop!
count = 0
while count < 5:
print(f"Count: {count}")
count += 1 # This is crucial to increment count and avoid infinite loop
# Example of a simple countdown
countdown = 3
while countdown > 0:
print(countdown)
countdown -= 1
print("Blast off!")
break and continue Statements
break: Terminates the current loop entirely and execution continues with the statement immediately following the loop.continue: Skips the rest of the current iteration of the loop and moves to the next iteration.
# Using break
for i in range(10):
if i == 5:
print("Breaking loop at 5")
break
print(i)
print("Loop finished (due to break)")
# Using continue
for i in range(10):
if i % 2 != 0: # If i is odd
continue # Skip this iteration
print(f"Even number: {i}")
print("Loop finished (with continue)")
Summary of Part 2
In this part, you've gained essential control over your program's flow by learning:
How to use
if,elif, andelsefor conditional execution.The role of comparison and logical operators in building conditions.
How to repeat code using
forloops (for definite iterations) andwhileloops (for indefinite iterations).How to control loop behavior with
breakandcontinue.
In Part 3, we'll explore Data Structures, learning how to organize and store collections of data efficiently in Python using lists, tuples, dictionaries, and sets! Get ready to level up your data handling!
Comments
Post a Comment