Control statements are the foundation of programming languages. These statements control the flow of execution in a program and allow developers to make decisions and execute certain code based on those decisions.
There are three different types of control statements:
- Sequential Statements
- Conditional Statements
- Iterative Statements
In this blog post, we will focus on the conditional and iterative statements in Python.
The "if" statement is a conditional statement that executes a block of code if a condition is true.
The syntax for an "if" statement is as follows:
if condition:
statement
Here is an example of an "if" statement in Python:
x = 10
if x > 5:
print("x is greater than 5")
The "if-else" statement is a conditional statement that executes one block of code if a condition is true, and another block of code if the condition is false.
The syntax for an "if-else" statement is as follows:
if condition:
statement
else:
statement
Here is an example of an "if-else" statement in Python:
x = 2
if x > 5:
print("x is greater than 5")
else:
print("x is less than or equal to 5")
The "nested if" statement is a conditional statement that contains another "if" statement within its block of code.
The syntax for a "nested if" statement is as follows:
if condition:
if condition:
statement
Here is an example of a "nested if" statement in Python:
x = 10
y = 5
if x > 5:
if y > 3:
print("Both x and y are greater than their respective values")
The "for" loop is an iterative statement that allows developers to loop through a sequence of values.
The syntax for a "for" loop is as follows:
for variable in sequence:
statement
Here is an example of a "for" loop in Python:
fruits = ["apple", "banana", "cherry"]
for x in fruits:
print(x)
The "while" loop is an iterative statement that executes a block of code as long as a condition is true.
The syntax for a "while" loop is as follows:
while condition:
statement
Here is an example of a "while" loop in Python:
i = 1
while i < 6:
print(i)
i += 1
Control statements are an essential part of any programming language. In Python, we have different types of control statements, including conditional and iterative statements. The "if" statement is a conditional statement that executes a block of code if a condition is true. The "if-else" statement is a conditional statement that executes one block of code if a condition is true and another block of code if the condition is false. The "nested if" statement is a conditional statement that contains another "if" statement within its block of code.