Lesson 3: Conditional Statements and Loops | Coding Class Series
Welcome to Lesson 3 of our Coding Class Series! In this lesson, we will learn how to make decisions in code using conditional statements and how to repeat tasks using loops. These are essential concepts in every programming language.
Conditional Statements (if-else)
Conditional statements help your program make decisions based on certain conditions.
# Example in Python
age = 18
if age >= 18:
print("You are an adult")
else:
print("You are a minor")
Explanation:
- If the condition
age >= 18is True, the first block of code executes. - If it is False, the code inside
elseexecutes.
Loops
Loops are used to repeat a block of code multiple times.
For Loop
# Print numbers from 0 to 4
for i in range(5):
print(i)
While Loop
count = 0
while count < 5:
print(count)
count += 1
Practice Exercises
- Write a program to check if a number is even or odd.
- Print numbers from 1 to 10 using a loop.
- Create a loop that sums all numbers from 1 to 100.
- Write a program to print only the numbers divisible by 3 between 1 and 50.
No comments:
Post a Comment