Lession 2: Control Structure by Copilot Github | Ballu Python 835430
### Lesson 2: Control Structures
Control structures allow you to control the flow of your program. In Python, the main control structures are conditional statements and loops.
#### 1. Conditional Statements
Conditional statements allow you to execute different blocks of code based on certain conditions.
**if Statement:**
```python
x = 10
if x > 5:
print("x is greater than 5")
```
**if-else Statement:**
```python
x = 3
if x > 5:
print("x is greater than 5")
else:
print("x is not greater than 5")
```
**if-elif-else Statement:**
```python
x = 7
if x > 10:
print("x is greater than 10")
elif x > 5:
print("x is greater than 5 but less than or equal to 10")
else:
print("x is 5 or less")
```
#### 2. Loops
Loops allow you to execute a block of code multiple times.
**for Loop:**
```python
# Loop through a list
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
# Loop through a range of numbers
for i in range(5):
print(i)
```
**while Loop:**
```python
# Loop while a condition is true
count = 0
while count < 5:
print(count)
count += 1
```
#### 3. Break and Continue Statements
**break Statement:**
The `break` statement is used to exit a loop prematurely.
```python
for i in range(10):
if i == 5:
break
print(i)
```
**continue Statement:**
The `continue` statement is used to skip the current iteration and continue with the next iteration.
```python
for i in range(10):
if i % 2 == 0:
continue
print(i)
```
### Practice Exercise:
1. Write a program that prints all the numbers from 1 to 20, but for multiples of 3, print "Fizz" instead of the number, and for multiples of 5, print "Buzz". For numbers which are multiples of both 3 and 5, print "FizzBuzz".
```python
for i in range(1, 21):
if i % 3 == 0 and i % 5 == 0:
print("FizzBuzz")
elif i % 3 == 0:
print("Fizz")
elif i % 5 == 0:
print("Buzz")
else:
print(i)
```
That's it for Lesson 2! Practice these control structures, and we'll move on to functions in the next lesson. Let me know if you have any questions!
Similar code found with 1 license type
Comments
Post a Comment