Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Unit Ii

Download as pdf or txt
Download as pdf or txt
You are on page 1of 9

Unit-II

Python Program Flow Control Conditional blocks: if, else and else if, Simple for loops in
python, For loop using ranges, string, list and dictionaries. Use of while loops in python, Loop
manipulation using pass, continue, break and else. Programming using Python conditional
and loop blocks.

In Python, flow control allows you to determine the order in which statements or code blocks
execute at runtime based on conditions. Let’s explore the key concepts:

Conditional Statements: These statements execute different blocks of code based on


whether a given condition is true or false.
There are three types of conditional statements:
• if statement: Executes a block of code if a condition is true.
• if-else statement: Executes one block if the condition is true and another block if it’s
false.
• if-elif-else statement: Handles multiple conditions sequentially.
• Nested if-else: Combines multiple conditions within each other.

Iterative Statements (Loops): These allow you to repeat a block of code as long as a condition
remains true.
Two common loop statements:
• for loop: Iterates over a sequence (e.g., a list, range, or string).
• while loop: Repeats as long as a specified condition holds true.

Transfer Statements: Alter the program’s execution flow:


• break: Exits the loop prematurely.
• continue: Skips the current iteration and moves to the next.
• pass: Acts as a placeholder (does nothing).

In Python, the if statement is used for conditional execution. It allows you to execute a block
of code only when a specific condition is met. Here’s how it works:

Python if Statement
An if statement executes a block of code only if the specified condition is met.
Syntax

if condition:
# body of if statement

Here, if the condition of the if statement is:


• True - the body of the if statement executes.
• False - the body of the if statement is skipped from execution.

PRAMOD KUMAR (ASST. PROFESSOR, CSE DEPARTMENT) 1


if number > 0:
print('Number is positive')

Here, the spaces before the print() statement denote that it's the body of the if statement.

number = 10

# check if number is greater than 0


if number > 0:
print('Number is positive')

print('This statement always executes')

output:
Number is positive
This statement always executes

if...else Statement
An if statement can have an optional else clause. The else statement executes if the condition
in the if statement evaluates to False.
Syntax

if condition:
# body of if statement

else:
# body of else statement

Here, if the condition inside the if statement evaluates to


• True - the body of if executes, and the body of else is skipped.
• False - the body of else executes, and the body of if is skipped

PRAMOD KUMAR (ASST. PROFESSOR, CSE DEPARTMENT) 2


Example: Python if…else Statement
number = 10

if number > 0:
print('Positive number')

else:
print('Negative number')

print('This statement always executes')

Output:

Positive number
This statement always executes

if…elif…else Statement
The if...else statement is used to execute a block of code among two alternatives.
However, if we need to make a choice between more than two alternatives, we use
the if...elif...else statement.
Syntax

if condition1:
# code block 1
elif condition2:
# code block 2
else:
# code block 3

Here,
• if condition1 - This checks if condition1 is True. If it is, the program executes code
block 1.

PRAMOD KUMAR (ASST. PROFESSOR, CSE DEPARTMENT) 3


• elif condition2 - If condition1 is not True, the program checks condition2.
If condition2 is True, it executes code block 2.
• else - If neither condition1 nor condition2 is True, the program defaults to
executing code block 3.

Let's look at an example.


number = 0

if number > 0:
print('Positive number')

elif number <0:


print('Negative number')

else:
print('Zero')

print('This statement is always executed')

Output

Zero
This statement is always executed

for Loop
In Python, a for loop is used to iterate over sequences such as lists, strings, tuples, etc.
languages = ['Swift', 'Python', 'Go']

# access elements of the list one by one


for i in languages:
print(i)

Output

PRAMOD KUMAR (ASST. PROFESSOR, CSE DEPARTMENT) 4


Swift
Python
Go

In the above example, we have created a list called languages. As the list has 3 elements, the
loop iterates 3 times.
The value of i is
• Swift in the first iteration.
• Python in the second iteration.

• Go in the third iteration.

for loop Syntax

for val in sequence:


# statement(s)

Here, val accesses each item of the sequence on each iteration. The loop continues until we
reach the last item in the sequence.
Flowchart of Python for Loop

Example: Loop Through a String


language = 'Python'
# iterate over each character in language
for x in language:
print(x)
Run Code
Output

P
y

PRAMOD KUMAR (ASST. PROFESSOR, CSE DEPARTMENT) 5


t
h
o
n

for Loop with Python range()


In Python, the range() function returns a sequence of numbers. For example,

values = range(4)

Here, range(4) returns a sequence of 0, 1, 2 ,and 3.


Since the range() function returns a sequence of numbers, we can iterate over it using
a for loop. For example,
# iterate from i = 0 to i = 3
for i in range(4):
print(i)
Run Code
Output

0
1
2
3

The range() Function


To loop through a set of code a specified number of times, we can use the range() function,
The range() function returns a sequence of numbers, starting from 0 by default, and
increments by 1 (by default), and ends at a specified number.
Example
Get your own Python Server
Using the range() function:
for x in range(6):
print(x)
Try it Yourself »

Note that range(6) is not the values of 0 to 6, but the values 0 to 5.


The range() function defaults to 0 as a starting value, however it is possible to specify the
starting value by adding a parameter: range(2, 6), which means values from 2 to 6 (but not
including 6):
Example:
Using the start parameter:
for x in range(2, 6):
print(x)

For loop using string


Even strings are iterable objects, they contain a sequence of characters:

PRAMOD KUMAR (ASST. PROFESSOR, CSE DEPARTMENT) 6


Example:
Loop through the letters in the word "banana":
for x in "banana":
print(x)

Output:
b
a
n
a
n
a

For loop using list:


You can loop through the list items by using a for loop:
Example:t your own Python Server

Print all items in the list, one by one:


thislist = ["apple", "banana", "cherry"]
for x in thislist:
print(x)

Output:

apple
banana
cherry

Python while Loop


In Python, we use the while loop to repeat a block of code until a certain condition is met.
For example,
number = 1

while number <= 3:


print(number)
number = number + 1
Output
1
2
3
while Loop Syntax
while condition:
# body of while loop
Here,
1. The while loop evaluates the condition.
2. If the condition is true, body of while loop is executed. The condition is evaluated
again.
3. This process continues until the condition is False.
PRAMOD KUMAR (ASST. PROFESSOR, CSE DEPARTMENT) 7
4. Once the condition evaluates to False, the loop terminates.

Example: Python while Loop


# Calculate the sum of numbers until user enters 0
number = int(input('Enter a number: '))
total = 0
# iterate until the user enters 0
while number != 0:
total += number
number = int(input('Enter a number: '))
print('The sum is', total)

Output

Enter a number: 3
Enter a number: 2
Enter a number: 1
Enter a number: -4
Enter a number: 0
The sum is 2

The break Statement


With the break statement we can stop the loop even if the while condition is true:
Example
Exit the loop when i is 3:
i=1
while i < 6:
print(i)
if i == 3:
break
i += 1

PRAMOD KUMAR (ASST. PROFESSOR, CSE DEPARTMENT) 8


The continue Statement
With the continue statement we can stop the current iteration, and continue with the next:
Example
Continue to the next iteration if i is 3:
i=0
while i < 6:
i += 1
if i == 3:
continue
print(i)

The else Statement


With the else statement we can run a block of code once when the condition no longer is
true:
Example
Print a message once the condition is false:
i=1
while i < 6:
print(i)
i += 1
else:
print("i is no longer less than 6")

PRAMOD KUMAR (ASST. PROFESSOR, CSE DEPARTMENT) 9

You might also like