0% found this document useful (0 votes)
7 views19 pages

Python Flow Control: If, Else, Loops

The document provides an overview of flow control in Python, focusing on conditional statements (if, else, elif) and loops (for, while). It explains how these constructs allow for decision-making and repetitive execution of code based on specific conditions. Additionally, it covers string manipulation, lists, dictionaries, and loop control statements like break, continue, and pass.

Uploaded by

shourya1jain234
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views19 pages

Python Flow Control: If, Else, Loops

The document provides an overview of flow control in Python, focusing on conditional statements (if, else, elif) and loops (for, while). It explains how these constructs allow for decision-making and repetitive execution of code based on specific conditions. Additionally, it covers string manipulation, lists, dictionaries, and loop control statements like break, continue, and pass.

Uploaded by

shourya1jain234
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

UNIT-2

Lecture 5. Flow Control Conditional if, else and else if

In Python, flow control structures such as if, else, and elif (else if) are used to implement conditional logic. These
constructs allow you to control the flow of your program based on different conditions.
Let's discuss how to use them:

2.1 Control flow statements in Python

First and foremost, Control flow statements in Python are how you direct your programs to decide which parts of

code to run. By default, programs execute each line of code in sequence, with understanding how things are

proceeding.

What if you don't want to execute every single line of code? What if you have several answers, and the code must

choose which one to utilize based on the conditions? What if you require the software to continually utilize the

same code to perform the computations with slightly different inputs? What if you want to execute a few lines of

code repeatedly until the application fulfills a condition? It is when control flow enters the picture. Control flow

statements in Python direct the flow of your program's execution. It allows you to make decisions, repeat actions,

and handle different situations to make your code more dynamic and adaptable.

2.2 Conditional Statements in Python

Conditional statements in Python are used to make decisions and execute different blocks of code based on specific

conditions. These conditions are defined using logical expressions that evaluate either True or False. Conditional

statements in Python control the flow of your program and enable it to respond dynamically to different situations.

2.2.1 if Statement:

The if statement is the most fundamental conditional statement in Python. It allows you to execute a block of code
only if a specified condition is true. If the condition evaluates to True, the code block is executed.

The if statement is used to execute a block of code only if a certain condition is true.

# Example of the if statement

x = 10
if x > 5:
print("x is greater than 5")
Output: x is greater than 5
22
2.2.2 if else Statement: The else statement is used to execute a block of code if the condition specified in the if
statement is false.

# Example of the if-else statement


y=3
if y > 5:
print("y is greater than 5")

else:
print("y is not greater than 5")
Output: y is not greater than 5

2.2.3 elif Statement:

The elif (else if) statement is used when there are multiple conditions to check. It allows you to check additional
conditions if the previous ones are false.

# Example of the if-elif-else statement

z=0
if z > 0:
print("z is positive")

elif z < 0:
print("z is negative")
else:
print("z is zero")
Output: z is zero

23
Lecture 6. Simple for loops, for loop using ranges.

2.3 Loops in Python

Iterative control statements in Python allow you to execute a block of code repeatedly. They perform repetitive

tasks, iterate over data structures, and handle various scenarios where actions need to be repeated.

Python has two main types of loops:

● The for loop

● The while loop

2.3.1 The for Loop

The for loop iterates over a sequence (such as a list, tuple, string, or range) or any other iterable object. It

executes ablock of code for each element in the sequence to perform actions on each element.

Example 1: Using for Loop with a List

Code

fruits = ["apple," "banana," "cherry"]

for fruit in fruits:

print(f"I love {fruit}s.")

Output:

code

I love apples.

I love bananas.

I love cherries.

In this example, the for loop iterates through the fruits list, and for each fruit, it executes the code block inside
24
the loop. This results in the message "I love [fruit]s." being printed for each item in the list.

Example 2: Using for Loop with a String

code

word = "Python"

for letters in words:

print(letter)

Output:

P
y
t
h
o
n

Here, the for loop iterates through the characters of the string "Python" and prints each character on a separate

line.

Example 3: Using for Loop with Range

code

for i in range(1, 6):


print(f" The Square of {i} is {i**2}.")

Output:

The square of 1 is 1.

The square of 2 is 4.

The square of 3 is 9.

The square of 4 is 16.

25
The square of 5 is 25.

This example uses the range() function to generate a sequence of numbers from 1 to 5 (inclusive). The for loop

then iterates through this sequence, calculating and printing the square of each number.

2.3.2 The while Loop

The while loop in Python repeatedly executes a block of code as long as a specified condition remains true. It

is useful when you need to repeat an action until a certain condition is met.

Example 1: Basic

while Loop Code

count = 1

while count <= 5:

print(f"The Count is {count}.")

count+ = 1

Output:

code
The count is 1.

The count is 2.

The count is 3.

The count is 4.

The count is 5.

In this example, the while loop continues to run as long as the condition (count <= 5) remains true.

Example 2: Using while Loop for User Input

26
Code

password = "secret"

user_input = input("Enter the password: )

while user_input != password:

print("Incorrect password. Try again.")

user_input = input("Enter the password: ")

print("Access granted.")

Output (assuming incorrect password inputs before entering "secret"):

Enter the password: incorrect Incorrect password. Try


again.
Enter the password: wrong pass
Incorrect password. Try again.
Enter the password: secret
Access granted.

This example uses a while loop to repeatedly prompt the user for a password until they enter the
correct password ("secret").

Example 3: Using While Loop with a Counter


Code
counter = 0
while counter < 3:
print(f"Processing item {counter}”)
counter+ = 1
Output:

Processing item 1

Processing item 2

Processing item 3

Here, the while loop is used to process items in a task. The loop continues until the counter reaches 3, at

which point it stops.

27
Lecture 7. String
2.4. String- Python string is the collection of the characters surrounded by single quotes, double quotes, or triple
quotes. The computer does not understand the characters; internally, it stores manipulated character as the
combination of the 0's and 1's.

Each character is encoded in the ASCII or Unicode character

a string is a sequence of characters enclosed in single (' '), double (" "), or triple (''' ''' or """ """) quotes. Strings
are immutable, meaning their values cannot be changed after creation.
some key aspects of working with strings in Python:

2.4.1 Creating Strings:

# Single quotes
single_quoted = 'Hello, Python!'

# Double quotes
double_quoted = "String in Python."

# Triple quotes for multiline string


s multiline = '''This is a
multiline string.'''

2.4.2 Accessing Characters in a String:

my_string = "Python"
# Accessing individual characters
first_char = my_string[0] #’P’

last_char = my_string[-1] # 'n'

2.4.3 String Slicing:

# Slicing a portion of a string


substring = my_string[1:4] #
'yth'

2.4.4 String Concatenation:

string1 = "Hello"
string2 = "Python"

28
# Concatenating strings
concatenated = string1 + " " + string2 # 'Hello Python'

2.4.5 String Methods:

Python provides various built-in string methods for manipulating and working with

strings. my_string = " Hello, Python! "

# Removing leading and trailing whitespaces


trimmed_string = my_string.strip() # 'Hello,
Python!'

# Converting to lowercase
lowercased = my_string.lower() # ' hello, python! '

# Converting to uppercase
uppercased = my_string.upper() # ' HELLO, PYTHON! '

# Finding substring
index = my_string.find("Python") # 8

2.4.6 String Formatting:

name = "Alice"
age = 30

# Using f-strings (Python 3.6 and above)


formatted_string = f"My name is {name} and I am {age} years old."

# Using the format method


formatted_string2 = "My name is {} and I am {} years old.".format(name, age)

2.4.7 String Operations:

# String length
length = len(my_string) #15
# Check if a substring is present

29
contains_python = "Python" in my_string #
True
# Repeat a string
repeated_string = my_string * 3 # ' Hello, Python! Hello, Python! Hello, Python! '

2.4.8 Escape Characters:

escaped_string = "This is a line.\nThis is a new line."


# Output:
This is a line.
This is a new line.

30
Lecture 8- List and dictionaries

2.5 Lists: A list is a versatile and mutable data structure in Python that can hold an ordered collection of items. Lists are
defined using square brackets [ ] and can contain elements of different data types.

2.5.1 Creating Lists:# Empty list


empty_list = []

2.5.2 List with elements


fruits = ['apple', 'banana', 'orange']

2.5.3 List with mixed data types


mixed_list = [1, 'two', 3.0, True]

2.5.4 Accessing List Elements:

# Accessing individual elements

first_fruit = fruits[0] # 'apple'


second_fruit = fruits[1] # 'banana'

2.5.5 Slicing a portion of a list


subset = fruits[1:3]
# ['banana', 'orange']

2.5.6 Modifying Lists:

# Modifying an element

fruits[0] = 'kiwi'

2.5.7 Appending to the end of the list


[Link]('grape')

2.5.8 Extending with another list

31
[Link](['pineapple', 'watermelon'])

2.5.9 List Operations:

# Length of a list

length = len(fruits) # 5

Check if an item is in the list


contains_banana = 'banana' in fruits # True

Concatenating list

more_fruits = ['pear', 'plum']


combined_list = fruits + more_fruits

2.6 Dictionaries:

A dictionary is an unordered collection of key-value pairs. It is defined using curly braces { } and colons : to
separate keys and values. Dictionaries are commonly used for data that needs to be looked up quickly.

2.6.1 Creating Dictionaries:


# Empty dictionary
empty_dict = {}

# Dictionary with key-value pairs


student = {'name': 'Alice', 'age': 25, 'grade': 'A'}

2.6.2 Accessing Dictionary Elements:


# Accessing values by key
student_name = student['name'] # 'Alice'

# Using the get method to avoid KeyErrors


student_age = [Link]('age') # 25

2.6.3 Modifying and Adding to Dictionaries:


# Modifying a value
student['age'] = 26

32
# Adding a new key-value pair
student['city'] = 'Wonderland'

2.6.4 Dictionary Operations:


# Length of a dictionary (number of key-value pairs)

dict_length = len(student) # 4

# Checking if a key is in the dictionary


has_grade = 'grade' in student # True

# Removing a key-value pair removed_grade =


[Link]('grade')

33
Lecture 9. Use of while loops in python

2.7 While loop- In Python, a while loop is used to repeatedly execute a block of code as long as a specified
condition is true. The loop continues to execute until the condition becomes false. Let's discuss how to use while
loops in Python:

2.7.1 Basic while Loop:

# Example of a basic while loop


count = 0
while count < 5:

print(f"Count: {count}")

count += 1

2.7.2 Infinite Loop:

# Example of an infinite while loop


while True:
user_input = input("Enter a number (type 'exit' to stop): ")

if user_input.lower() == 'exit':
break # Exit the loop if 'exit' is entered

else:
print(f"You entered: {user_input}")

2.7.3 Using else with while:

# Example of using else with while


loop num = 0

while num < 5:

print(f"Num: {num}")

34
num += 1
else:
print("Loop finished.")

2.7.4 while Loop with continue:

# Example of using continue in a while loop num = 0


while num < 5:
num += 1
if num == 3:
continue # Skip the rest of the code
in the loop for num == 3

print(f"Num: {num}")
The continue statement is used to skip the remaining code inside the loop for the current iteration and move
to the next iteration.

2.7.5 while Loop with else and break:

# Example of using else and break in a while loop num = 0


while num < 5:’
print(f"Num: {num}")
num += 1
if num == 3:
break # Exit the loop when num == 3 else:
print("Loop finished.")

In this example, the else block is not executed because the loop is terminated by the break statement.

35
Lecture 10. Loop manipulation using pass continue, break and else.

2.8 Manipulation Statements- In Python, loop manipulation statements like pass, continue, break, and else provide
ways to control the flow of loops.

2.8.1 pass Statement:

The pass statement is a no-operation statement that serves as a placeholder when syntactically some code is
required, but you don't want to execute any specific operation.

for i in range(5):

if i == 2:

pass # Do nothing when i is 2

else:

print(i)

# Output:
#0
#1
#3
#4

2.8.2 continue Statement:

The continue statement is used to skip the rest of the code inside the loop for the current iteration and move to
the next iteration.

for i in range(5):
if i == 2:
continue # Skip printing when i is 2
print(i)
#Output:
#0
#1
#3

36
#4

2.8.3 break Statement:


The break statement is used to exit the loop prematurely. It terminates the loop when a specified condition is met.

for i in range(5):
if i == 3:
break # Exit the loop when i is 3
print(i)
# Output:
#0
#1
#2

2.9 else Clause in Loops:

The else clause in a loop is executed when the loop condition becomes False. However, if the loop is terminated
by a break statement, the else clause is skipped.

for i in range(5):
print(i)
else:
print("Loop finished.")
# Output:
#0
#1
#2
#3
#4
# Loop finished.
for i in range(5):
if i == 3:
break # Exit the loop when i is 3 print(i)
else:
print("Loop finished.")

# Output:
#0
#1
#2

37
Lecture 11. Condition and loop blocks in Program.

2.10 Condition Blocks: Condition blocks are used to execute specific blocks of code based on whether a certain
condition is true or false.

2.10.1 if Statement:
x = 10
if x > 5:
print("x is greater than 5")

2.10.2 else Statement:


y=3
if y > 5:
print("y is greater than 5")
else:
print("y is not greater than 5")

2.10.3 elif Statement:

z=0
if z > 0:
print("z is positive")

elif z < 0:
print("z is negative")
else:
print("z is zero")

2.11 Loop Blocks:

Loop blocks are used for repeating a block of code multiple times.

for Loop:
fruits = ['apple', 'banana', 'orange']

for fruit in fruits:


print(fruit)

38
while Loop:
count = 0
while count < 5:
print(f"Count: {count}")
count += 1

2.12 Combining Condition and Loop Blocks:

You can also use conditionals within loops to create more complex control structures.

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]

for num in numbers:


if num % 2 == 0:
print(f"{num} is even")
else:
print(f"{num} is odd")

2.13 Nested Blocks:

You can nest conditionals and loops within each other for more intricate program logic.

for i in range(3):
if i == 0:
print("First iteration")
else:
print("Not the first iteration")

Important Ques Unit-2

i. How pass statement is different from comment? (2021-22)


ii. Explain the use of BREAK and CONTINUE statement with example . (2022-23)
iii. In Some languages, every statement ends with a semicolon(;) , what happens if you put a semi-colon at the
end of a python statement.(2019-20)
iv. Explain the purpose and working of loops with their flowchart , syntax and suitable example.(2022-23)
v. Write a python program to construct the following pattern , using a nested for loop.(2021-22)

*
39
**
***
****
*****
****
***
**
*

40

You might also like