1969 - 982 - DOC - Control Flow in Python
1969 - 982 - DOC - Control Flow in Python
Welcome to this session on Control Flow in Python! This guide will help you understand and
apply control structures in your Python programs, focusing on if-else statements and loops.
Examples:
1. Voting Eligibility Check
Python
age = 18
2. Temperature Check
Python
temperature = 30
3. Number Comparison
Python
a = 10
b = 20
if a > b:
print("a is greater than b")
else:
print("a is not greater than b")
2. Loops
What is a Loop?
A loop allows you to repeat a block of code multiple times. There are two main types of loops in
Python:
1. For Loop
2. While Loop
Python
for item in sequence:
# Code to execute for each item
Examples:
1. Iterating Over a List
Python
fruits = ["apple", "banana", "cherry"]
2. Range Loop
Python
for i in range(5):
print(i)
3. String Iteration
Python
word = "Python"
Python
while condition:
# Code to execute while the condition is True
Examples:
1. Counting with While Loop
Python
count = 1
Python
user_input = ""
3. Decrementing Loop
Python
n = 5
while n > 0:
print(n)
n -= 1
Task:
Write a Python program that asks the user to input a number. The program should then print
whether the number is positive, negative, or zero. After that, the program should print all the
numbers from 1 to the input number using a loop.
Solution:
Python
# Get user input
number = int(input("Enter a number: "))
By mastering these concepts, you’ll be well on your way to writing more complex and efficient
Python programs.
Total: 18 minutes
Happy coding! 😊