In any programming language there are three constructs that provide the fundamental building blocks for structuring and controlling the execution flow in programming languages. Before you bein, you should probably be aware of what different data types you can find in Python as well as what a variable is. Read this post first if you are unsure — Ready? Let’s take a look;
Sequence
The sequence concept refers to the execution of statements in a particular order, one after the other.
Example:
# Example of sequence
name = "Alice"
age = 25
print("Name:", name)
print("Age:", age)
Output
Name: Alice
Age: 25
In this example, the statements are executed in a sequential manner. First, the variable name is assigned the value “Alice,” and then the variable age is assigned the value 25. Finally, the values of name and age are printed in order.
Selection (Conditional Statements):
Selection allows the program to execute different code blocks based on certain conditions. In Python, conditional statements like if, elif, and else are used for selection.
Example:
# Example of selection
temperature = 28
if temperature > 30:
print("It's a hot day!")
elif temperature < 20:
print("It's a cold day!")
else:
print("It's a moderate day!")
Output
It's a moderate day!
Iteration
Iteration allows the repetition of a block of code until a certain condition is met. Two common iteration structures in Python are for and while loops.
# Example of iteration with a for loop
fruits = ["apple", "banana", "orange"]
for fruit in fruits:
print(fruit)
Output:
apple
banana
orange
In this example, the for loop iterates over each element in the fruits list and prints it.
Example of iteration with a while loop
count = 1
while count <= 5:
print("Count:", count)
count += 1
Output:
Output
Copy code
Count: 1
Count: 2
Count: 3
Count: 4
Count: 5
In this example, the while loop repeats the block of code until the count variable becomes greater than 5. It prints the value of count in each iteration and increments it by 1.
These examples demonstrate the fundamental concepts of sequence, selection, and iteration in Python programming.