In Python, control statements are statements that allow you to control the flow of execution in the program. These statements alter the order in which instructions are executed in your code, based on certain conditions.
Python has three types of conditional statements:
if, elif, and else. These statements are used to control the flow of execution in a program based on certain conditions.
Example:
x = 5
if x > 0:
print("x is positive")
In this example, the condition x > 0 is true, so the block of code inside the if statement is executed, which prints "x is positive" to the console.
Example:
x = 0
if x > 0:
print("x is positive")
else:
print("x is zero")
In this example, the condition x > 0 is false, so the block of code inside the else statement is executed, which prints "x is zero" to the console.
Example:
x = 0
if x > 0:
print("x is positive")
elif x < 0:
print("x is negative")
else:
print("x is zero")
In this example, the condition x > 0 is false, and the condition x < 0 is true, so the block of code inside the elif statement is executed, which prints "x is negative" to the console.
In Python, there are three main types of looping statements: for, while, and nested loops. Each type of loop serves a specific purpose and can be used to accomplish a variety of tasks.
for variable in sequence:
# do something with variable
Here, the variable takes on the value of each item in the sequence, and the loop body is executed once for each item in the sequence.
fruits = ["apple", "banana", "cherry"]
for x in fruits:
print(x)
for i in range(start, stop, step):
# do something with i
Example
for i in range(1, 5):
print(i)
OUTPUT:
1
2
3
4
for i, item in enumerate(sequence):
# do something with i and item
Example:
fruits = ["apple", "banana", "cherry"]
for i, fruit in enumerate(fruits):
print(i, fruit)
OUTPUT:
0 apple
1 banana
2 cherry
for item1, item2, ... in zip(sequence1, sequence2, ...):
# do something with item1, item2, ...
Example:
fruits = ["apple", "banana", "cherry"]
colors = ["red", "yellow", "green"]
for fruit, color in zip(fruits, colors):
print(fruit, color)
OUTPUT:
apple red
banana yellow
cherry green
new_list = [expression for item in sequence if condition]
Example:
numbers = [1, 2, 3, 4, 5]
squares = [num**2 for num in numbers]
print(squares)
OUTPUT:
[1, 4, 9, 16, 25]
while condition:
# do something
count = 0
while count < 5:
print(count)
count += 1
OUTPUT:
0
1
2
3
4
for i in range(10):
if i == 5:
break
print(i)
In this example, the loop will print the values of i from 0 to 4, and then exit when i equals 5. The output will be:
0
1
2
3
4
for i in range(10):
if i == 5:
continue
print(i)
In this example, the loop will print the values of i from 0 to 9, but skip over the value of 5. The output will be:
0
1
2
3
4
6
7
8
9
def my_function():
pass
In this example, my_function() is defined but does not contain any code. This can be useful when you want to write the function skeleton before filling in the details.
Advertisement
Advertisement