Day 3: Control Flow Statements: Conditionals and Loops
Welcome to Day 3 of our 90-day journey to learn core Python! Yesterday, we covered basic syntax, variables, data types, and operators. Today, we’ll dive into control flow statements, which allow us to make decisions and repeat actions in our programs. Let’s get started!
Conditionals: if, elif, and else Statements
Conditionals are used to perform different actions based on specific conditions. In Python, we use if
, elif
(short for "else if"), and else
statements. Here's an example:
age = 18
if age < 18:
print("You are underage.")
elif age >= 18 and age < 65:
print("You are an adult.")
else:
print("You are a senior citizen.")
By using conditionals, we can execute different blocks of code based on the given conditions.
Loops: for and while Statements
Loops enable us to repeat a block of code multiple times. Python provides two types of loops: for
and while
.
The for
loop is used when we know the number of iterations in advance. Here's an example that prints the numbers from 1 to 5:
for i in range(1, 6):
print(i)
The while
loop is used when we want to repeat a block of code until a specific condition is met. For example, let's print numbers from 1 to 5 using a while
loop:
i = 1
while i <= 5:
print(i)
i += 1
Loops allow us to automate repetitive tasks and process large amounts of data efficiently.
Control Flow: break, continue, and pass Statements
In addition to conditionals and loops, Python provides control flow statements to modify the behavior of our code.
- The
break
statement terminates the loop prematurely. - The
continue
statement skips the rest of the current iteration and moves to the next one. - The
pass
statement is used as a placeholder when no action is required.
These control flow statements provide flexibility and allow us to fine-tune the execution of our code.
Conclusion
Congratulations on completing Day 3 of our Python learning journey! Today, we explored control flow statements, including conditionals (if
, elif
, else
), loops (for
and while
), and control flow modifiers (break
, continue
, pass
). These concepts are fundamental to building robust and dynamic programs.
Take some time to practice using conditionals and loops in your code. Tomorrow, on Day 4, we’ll delve into functions, a powerful tool for organizing and reusing code.
Keep up the great work, and I’ll see you tomorrow for Day 4! Happy coding! 🚀
Note: This blog post is part of a 90-day series to teach core Python programming from scratch. If you missed any previous days, you can find them in the series index here.