Control statements:
In Python, control statements are used to direct the flow of execution in a program. They allow you to make decisions, repeat actions, and branch the flow of control.|
There are two types of control statements. they are:
1.Conditional statements.
2.Itreative statements
1. Conditional Statements
Conditional statements are used to perform different actions based on different conditions. The most common conditional statement is the if
statement.
There are situations in real life when we need to do some specific task and based on some specific conditions, we decide what we should do next. Similarly, there comes a situation in programming where a specific task is to be performed if a specific condition is True. In such cases, conditional statements can be used. The following are the conditional statements provided by Python.
1.if Statements
2.if-else Statements
3.if-elif Statements
4.Nested if Statements
1.if Statement in python
If the simple code of block is to be performed if the condition holds true then the if statement is used. Here the condition mentioned holds then the code of the block runs otherwise not.
Python if Statement Syntax
Syntax: if condition:
# Statements to execute if
# condition is true
Example:
age = 18
if age >= 18:
print(“You are eligible to vote.”)
2.if else Statement in Python
In conditional if Statement the additional block of code is merged as else statement which is performed when if condition is false. means The if-else
statement provides an alternative block of code that executes when the condition evaluates to False
.
syntax:
if condition:
# Code block to execute if the condition is True
else:
# Code block to execute if the condition is False
example:
age = 16
if age >= 18:
print(“You are eligible to vote.”)
else:
print(“You are not eligible to vote.”)
Nested if..else Chain for Multiple Conditions:
You can also chain if..else statement with more than one condition. In this example, the code uses a nested if..else
chain to check the value of the variable letter
. It prints a corresponding message based on whether letter
is “B,” “C,” “A,” or none of the specified values, illustrating a hierarchical conditional structure.
example:
if..else chain statement
letter = "A"
if letter == "B":
print("letter is B")
else:
if letter == "C":
print("letter is C")
else:
if letter == "A":
print("letter is A")
else:
print("letter isn't A, B and C")
if-elif-else
Statement:
the if-elif-else statement allows checking multiple conditions sequentially until one of them is TrueIf none of the conditions is True, the else block is executed.
syntax:
if condition1:
# Code block to execute if condition1 is True
elif condition2:
# Code block to execute if condition2 is True
elif condition3:
# Code block to execute if condition3 is True
else:
# Code block to execute if all above conditions are False
Example:
score = 85
if score >= 90:
print("Grade: A")
elif score >= 80:
print("Grade: B")
elif score >= 70:
print("Grade: C")
else:
print("Grade: D")
Various loop statements:
What is looping statement?
Loops in Python are used to execute a block of code repeatedly. They are fundamental to programming as they allow automation of repetitive tasks.
Types of itterative statements :
1.While 2.For loop
3.Nested loop 4.Infinate loop
5.Break 6.continue
7.Assert 8.pass
1.While Loop in Python
while loop is used to execute a block of statements repeatedly until a given condition is satisfied. When the condition becomes false, the line immediately after the loop in the program is executed.
Python While Loop Syntax:
while expression:
statement(s)
Example program:
count = 0
while (count < 3):
count = count + 1
print(“Hello bhanu”)
–
The given Python code uses a ‘while'
loop to print “Hello bhanu” three times by incrementing a variable called ‘count'
from 1 to 3.
2.For loop in python:
In Python, for
loops are a handy tool for iterating over a sequence, such as a list, string, or array. They allow you to go through each item in a sequence one by one, making them perfect for tasks like processing elements in a list or characters in a string. If you’re familiar with the foreach
loop from other programming languages, Python’s for
loop works in a similar way.
syntax:
for item in sequence:
# do something with item
here:item
is a variable that takes the value of each element in the sequence, one at a time.sequence
is the collection of items you want to iterate over, such as a list or a string.
Example::
n = 4
for i in range(0, n):
print(i)
The code uses a Python for loop that iterates over the values from 0 to 3 (not including 4), as specified by the range(0, n)
construct. It will print the values of ‘i'
in each iteration of the loop.
Example 2:
bp= “bhanu”
for letter in bp:
print(letter)
3. Nested Loop:
A nested loop is a nothing but loop inside another loop. You can use them when you need to perform repeated actions within repeated actions, such as iterating over a matrix.
syntax:
for item1 in sequence1:
for item2 in sequence2:
# code to execute
Example:
for i in range(3):
for j in range(2):
print(f”i = {i}, j = {j}”)
4. Infinite Loop:
An infinite loop is a loop that never ends on its own because the loop condition always remains true. These loops are often used to keep a program running until a specific event occurs.
syntax:
while True:
# code to execute
Example:
while True:
print(“bhanu”)
5. Break:
The break statement is used to exit a loop prematurely. It stops the current loop and resumes execution at the next statement after the loop.
syntax:
for item in sequence:
if condition:
break
# code to execute
Example:
for number in range(10):
if number == 5:
break
print(“Number:”, number)
The loop stops as soon as it encounters the number 5, breaking out of the loop.
6. Continue:
The continue statement skips the rest of the code inside the loop for the current iteration and moves to the next iteration.
syntax:
for item in sequence:
if condition:
continue
# code to execute
Example:
for number in range(5):
if number == 2:
continue
print(“Number:”, number)
This loop skips the number 2 and continues with the next numbers.
7. Assert
The assert statement is used for debugging purposes. It tests if a condition is true. If it isn’t, the program will raise an AssertionError
and optionally display an error message.
Syntax:
assert condition, “Error message”
Example:
x = 5
assert x > 0, “x should be positive”
In this example, if x
is not greater than 0, an error will be raised with the message “x should be positive.”
8. Pass:
The pass statement is a placeholder that does nothing. It’s used when a statement is required syntactically but no code needs to be executed.
Syntax:
for item in sequence:
if condition:
pass # Placeholder for future code
# code to execute
Example:
for number in range(5):
if number == 3:
pass # placeholder for future code
print(“Number:”, number)
Here, pass
does nothing when number
is 3, and the loop continues as usual.
Example programs:
program for calculates the sum of all elements in a list using a for
loop:
numbers = [1, 2, 3, 4, 5]
total_sum = 0
for number in numbers:
total_sum += number
print("Sum of elements:", total_sum)
program for prints a simple pattern using a nested for
loop.
rows = 5
for i in range(1, rows + 1):
for j in range(i):
print("*", end="")
print()
output:
*
**
***
****
*****
program for calculates the factorial of a number using a while
loop.
number = 5
factorial = 1
while number > 0:
factorial *= number
number -= 1
print("Factorial:", factorial)