syntax and examples:
# Flow Control with Decisions and Loops
Programming often requires making decisions based on conditions and repeating tasks multiple times. We
can control the flow of a program using conditional statements like if-else and loops like for and while.
## If-Else Statements
If-else statements allow us to execute code only when certain conditions are met.
**Syntax:**
```
if condition:
# code to execute if condition is True
else:
# code to execute if condition is False
```
**Example:**
```python
x = 10
if x > 5:
print("x is greater than 5")
else:
print("x is less than or equal to 5")
```
Here, the if block will execute since x meets the condition x > 5.
We can chain multiple if-elif-else blocks to check multiple conditions:
**Syntax:**
```
if condition1:
# code
elif condition2:
# code
else:
# code
```
**Example:**
```python
score = 85
if score >= 90:
print("A")
elif score >= 80:
print("B")
elif score >= 70:
print("C")
else:
print("F")
```
This will print "B" since the elif condition score >= 80 is the first one to evaluate to True.
## For Loops
For loops allow us to repeat a block of code multiple times.
**Syntax:**
```
for variable in iterable:
# code to repeat
```
**Example:**
```python
for i in range(5):
print(i) # Prints 0, 1, 2, 3, 4
for letter in 'Python':
print(letter) # Prints 'P', 'y', 't', 'h', 'o', 'n'
```
We can use break and continue statements inside for loops:
- break: Completely terminate the closest enclosing loop
- continue: Skip to the next iteration of the closest enclosing loop
## While Loops
While loops repeatedly execute code as long as a condition is True.
**Syntax:**
```
while condition:
# code to repeat
```
**Example:**
```python
count = 0
while count < 5:
print(count)
count += 1
```
This prints the numbers 0 through 4. We can use break and continue in while loops too.
## Summary
- If-else statements allow us to execute code based on conditions
- For loops iterate over iterables like ranges and collections
- While loops repeat code as long as a condition is True
- break and continue statements modify loop execution flow
By mastering conditionals and loops, we gain precise control over program flow.
branching statements like if, elif, else, nested conditions, and compound conditional expressions in
Python.
Example 1: Simple if-else statement
python
x = 10
if x > 0:
print("x is positive")
else:
print("x is non-positive")
Example 2: If-elif-else ladder
python
score = 75
if score >= 90:
grade = 'A'
elif score >= 80:
grade = 'B'
elif score >= 70:
grade = 'C'
elif score >= 60:
grade = 'D'
else:
grade = 'F'
print("Your grade is:", grade)
Example 3: Nested if statements
python
x = 10
y=5
if x > 0:
if y > 0:
print("Both x and y are positive")
else:
print("x is positive but y is non-positive")
else:
print("x is non-positive")
Example 4: Compound conditional expressions
python
x = 10
y=5
if x > 0 and y > 0:
print("Both x and y are positive")
elif x > 0 and y <= 0:
print("x is positive but y is non-positive")
else:
print("x is non-positive")
These examples showcase different ways to use branching statements in Python for flow control. They
demonstrate how to make decisions and control the flow of your code based on certain conditions.
User
write the content & hands on content on the following topics Flow Control with Decisions and Loops
Construct and analyze code segments that use branching statements
• if, elif, else, nested and compound conditional expressions
Flow Control with Decisions and Loops
Flow control is an essential concept in programming, allowing you to direct the execution of your code
based on certain conditions or iterate over a sequence of instructions multiple times. In this guide, we'll
explore how to construct and analyze code segments that use branching statements, including if, elif, else,
nested conditions, and compound conditional expressions.
1. If, elif, else Statements
The if, elif (short for "else if"), and else statements are used to control the flow of a program based on
specific conditions.
python
age = 18
if age < 18:
print("You are a minor.")
elif age == 18:
print("You just reached adulthood!")
else:
print("You are an adult.")
2. Nested Conditions
Nested conditions involve placing one if statement within another, allowing for more complex decision-
making processes.
python
x = 10
y = -5
if x > 0:
if y > 0:
print("Both x and y are positive.")
else:
print("x is positive but y is non-positive.")
else:
print("x is non-positive.")
3. Compound Conditional Expressions
Compound conditional expressions use logical operators (and, or, not) to combine multiple conditions
into a single expression.
python
temperature = 25
time_of_day = "morning"
if temperature > 20 and time_of_day == "morning":
print("It's a warm morning!")
elif temperature <= 20 and time_of_day == "morning":
print("It's a cool morning.")
else:
print("Weather conditions are unknown.")
Exercise: Determine Leap Year
Write a Python program to determine whether a given year is a leap year or not. A leap year is divisible
by 4, but not by 100 unless it is also divisible by 400.
python
def is_leap_year(year):
if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0):
return True
else:
return False
# Test the function
year = int(input("Enter a year: "))
if is_leap_year(year):
print(year, "is a leap year.")
else:
print(year, "is not a leap year.")