Learn Python This Summer:Day 4: Control Structures

Welcome back! Yesterday, we learned about data types and operators in Python. Today, we’ll explore control structures, which allow us to control the flow of our programs using conditions and loops. By the end of this day, you’ll be able to write Python programs that make decisions and repeat actions. Let’s get started!

If Statements
If statements allow your program to execute certain blocks of code only if specific conditions are met. Here’s the basic syntax:

python
Copy code
if condition:

Code to execute if the condition is true

elif another_condition:

Code to execute if the another_condition is true

else:

Code to execute if none of the conditions are true

Example:

python
Copy code
age = 14

if age < 13:
print("You are a child.")
elif age < 18:
print("You are a teenager.")
else:
print("You are an adult.")
For Loops
For loops are used to iterate over a sequence (like a list or a string) and execute a block of code for each item in the sequence.

python
Copy code
fruits = ["apple", "banana", "cherry"]

for fruit in fruits:
print(fruit)
You can also use the range() function to generate a sequence of numbers:

python
Copy code
for i in range(5):
print(i)
While Loops
While loops repeat a block of code as long as a specified condition is true.

python
Copy code
count = 0

while count < 5:
print(count)
count += 1
Nested Loops
You can nest loops inside each other. This is useful for working with multi-dimensional data structures like lists of lists.

python
Copy code
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]

for row in matrix:
for item in row:
print(item, end=’ ‘)
print()
Break and Continue
Break: Exits the loop immediately.
Continue: Skips the rest of the code inside the loop for the current iteration and moves to the next iteration.
Example:

python
Copy code
for i in range(10):
if i == 5:
break
print(i)

for i in range(10):
if i % 2 == 0:
continue
print(i)
Practice Time!
Let’s put what we’ve learned into practice. Write a Python program that uses if statements, for loops, and while loops.

python
Copy code

If statements

temperature = 25

if temperature > 30:
print("It’s a hot day.")
elif temperature > 20:
print("It’s a nice day.")
else:
print("It’s a cold day.")

For loop

numbers = [1, 2, 3, 4, 5]

for number in numbers:
print(number * number)

While loop

count = 10

while count > 0:
print(count)
count -= 1
Conclusion
Great job today! You’ve learned how to use control structures to make decisions and repeat actions in your Python programs. Tomorrow, we’ll dive into functions, which allow us to organize and reuse code. Keep practicing and having fun coding!

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *