Welcome to Day 3 of the 30 Days of Data Science series! Today, we will cover essential programming constructs—If-Else Statements and Loops—which are fundamental for controlling the flow of your Python programs. Let’s dive in!
if condition:
# Code block executed if the condition is True
else:
# Code block executed if the condition is Falseage = 20
if age >= 18:
print("You are an adult!")
else:
print("You are a minor!")Output:
You are an adult!
age = 16
if age >= 18:
print("You can vote!")
else:
if age >= 16:
print("You are a teenager!")
else:
print("You are a child!")Output:
You are a teenager!
marks = 85
if marks >= 90:
print("Grade: A")
elif marks >= 75:
print("Grade: B")
elif marks >= 50:
print("Grade: C")
else:
print("Grade: F")Output:
Grade: B
Loops allow repetitive tasks to be performed efficiently.
The for loop iterates over a sequence (like a list, tuple, or string).
for item in sequence:
# Code block to execute for each itemnumbers = [1, 2, 3, 4, 5]
for num in numbers:
print(num)Output:
1
2
3
4
5
The while loop executes a block of code as long as a condition is True.
while condition:
# Code block to executecount = 0
while count < 5:
print(count)
count += 1Output:
0
1
2
3
4
- Break: Terminates the loop prematurely.
- Continue: Skips the current iteration and moves to the next.
for num in range(1, 6):
if num == 3:
break # Exit loop when num is 3
print(num)Output:
1
2
for num in range(1, 6):
if num == 3:
continue # Skip iteration when num is 3
print(num)Output:
1
2
4
5
- Write a program that checks if a number is positive, negative, or zero.
- Create a grade classifier using the if-elif-else structure.
- Write a program that prints all even numbers from 1 to 50 using a for loop.
- Create a program that sums the numbers from 1 to 100 using a while loop.
- Use break and continue in a loop to demonstrate their functionality.
- If-Else Statements allow you to make decisions in your code.
- Loops enable you to automate repetitive tasks efficiently.
- Break and Continue give more control over loop execution.