Experiment 5
Experiment 5
Roll no:55
Div& Class:TY CSE B
Experiment Title : Flow control in python
Experiment no 5: To implement programs based on flow control in python
Flow control is a crucial concept in programming that determines the order in which
statements are executed. In Python, flow control is managed using conditional
statements (`if`, `elif`, `else`) and loops (`for`, `while`). These constructs allow a
program to make decisions and repeat actions, providing flexibility and dynamism in
code execution.
Conditional statements allow the execution of code based on certain conditions. The
`if` statement evaluates a condition, and if the condition is true, the block of code
under it is executed. If the condition is false, the code under `else` (if present) is
executed.
- **`if-else` Statement:**
- The `if` statement checks a condition. If it’s true, the code inside the `if` block is
executed. If false, the code inside the `else` block is executed.
Example:
x = 10
if x > 5:
print("x is greater than 5")
else:
print("x is not greater than 5")
- In this example, since `x` is greater than 5, the first print statement is executed.
- **`elif` Statement:**
- `elif` stands for "else if" and is used to check multiple conditions. If the first `if`
condition is false, the program checks the `elif` condition(s). If an `elif` condition
is true, its corresponding block of code is executed. If none of the conditions are
true, the `else` block is executed.
- Example:
```python
x = 10
if x > 15:
print("x is greater than 15")
elif x > 5:
print("x is greater than 5 but not greater than 15")
else:
print("x is 5 or less")
```
- Here, since `x` is 10, the `elif` block is executed.
Loops allow the repetition of a block of code multiple times. Python provides two
types of loops: `for` and `while`.
- **`for` Loop:**
- The `for` loop iterates over a sequence (like a list, tuple, dictionary, set, or
string) and executes a block of code for each item in the sequence.
- Example:
```python
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
```
- This loop will print each fruit in the `fruits` list.
- **`while` Loop:**
- The `while` loop continues to execute a block of code as long as the given
condition remains true. It checks the condition before each iteration.
- Example:
```python
i=1
while i < 5:
print(i)
i += 1
```
- This loop prints numbers from 1 to 4. The loop stops when `i` becomes 5.