unit 2
unit 2
UNIT 2
Selection Control: If Statement- Indentation in Python- Multi-Way Selection - Iterative
Control: While Statement- Infinite loops- Definite vs. Indefinite Loops.
Lists: List Structures - Lists (Sequences) in Python - Python List Type - Tuples - Sequences -
Nested Lists.
SELECTION CONTROL:
IF STATEMENT
if statement is the most simple decision-making statement. If the condition evaluates to True, the
block of code inside the if statement is executed.
If Statement
Example of If Statement:
i = 10
IF....ELSE STATEMENT
1
Let's look at some examples of if-else statements.
Simple if-else
i = 20
If Else in One-line
If we need to execute a single statement inside the if or else block then one-line shorthand can be
used.
a = -2
Output
Negative
We can combine multiple conditions using logical operators such as and, or, and not.
age = 25
exp = 10
Output
Eligible.
2
NESTED IF ELSE STATEMENT
Nested if...else statement occurs when if...else structure is placed inside another if or else block.
Nested If..else allows the execution of specific code blocks based on a series of conditional
checks.
Nested if Statement
Example of Nested If Else Statement:
i = 10
if (i == 10):
# First if statement
if (i < 15):
print("i is smaller than 15")
# Nested - if statement
# Will only be executed if statement above
# it is true
if (i < 12):
print("i is smaller than 12 too")
else:
print("i is greater than 15")
else:
print("i is not equal to 10")
IF…ELIF…ELSE STATEMENT
if-elif-else statement in Python is used for multi-way decision-making. This allows us to check
multiple conditions sequentially and execute a specific block of code when a condition is True. If
none of the conditions are true, the else block is executed.
3/3
Example:
i = 25
# Checking if i is equal to 10
if (i == 10):
print("i is 10")
# Checking if i is equal to 15
3
elif (i == 15):
print("i is 15")
# Checking if i is equal to 20
elif (i == 20):
print("i is 20")
USING INDENTATION
In the examples which have appeared in this chapter so far, there has only been one statement
appearing in the if body. Of course it is possible to have more than one statement there; for
example:
if choice == 1:
count += 1
print("Thank you for using this program.")
print("Always print this.") # this is outside the if block
The interpreter will treat all the statements inside the indented block as one statement – it will
process all the instructions in the block before moving on to the next instruction. This allows us
to specify multiple instructions to be executed when the condition is met.
if is referred to as a compound statement in Python because it combines multiple other
statements together. A compound statement comprises one or more clauses, each of which has
a header (like if) and a suite (which is a list of statements, like the if body). The contents of the
suite are delimited with indentation – we have to indent lines to the same level to put them in the
same block.
Python supports two types of loops: for loops and while loops. Alongside these
loops, Python provides control statements like continue, break, and pass to manage the flow of
the loops efficiently. This article will explore these concepts in detail.
Table of Content
for Loops
while Loops
Control Statements in Loops
o break Statement
4
o continue Statement
o pass Statement
FOR LOOPS
A for loop in Python is used to iterate over a sequence (such as a list, tuple, string, or range).
# Iterating over a list
a = [1, 2, 3]
for i in a:
print(i)
Output
1
2
3
WHILE LOOPS
A while loop in Python repeatedly executes a block of code as long as a given condition is True.
# Using while loop
cnt = 0
while cnt < 5:
print(cnt)
cnt += 1
Output
0
1
2
3
4
CONTROL STATEMENTS IN LOOPS
Control statements modify the loop's execution flow. Python provides three primary control
statements: continue, break, and pass.
break Statement
The break statement is used to exit the loop prematurely when a certain condition is met.
# Using break to exit the loop
for i in range(10):
if i == 5:
break
print(i)
5
Output
0
1
2
3
4
Explanation:
The loop prints numbers from 0 to 9.
When i equals 5, the break statement exits the loop.
CONTINUE STATEMENT
The continue statement skips the current iteration and proceeds to the next iteration of the loop.
# Using continue to skip an iteration
for i in range(10):
if i % 2 == 0:
continue
print(i)
Output
1
3
5
7
9
Explanation:
The loop prints odd numbers from 0 to 9.
When i is even, the continue statement skips the current iteration.
pass Statement
The pass statement is a null operation; it does nothing when executed. It's useful as a placeholder
for code that you plan to write in the future.
# Using pass as a placeholder
for i in range(5):
if i == 3:
pass
print(i)
Output
0
6
1
2
3
4
Explanation:
The pass statement does nothing and allows the loop to continue executing.
It is often used as a placeholder for future code.
In Python, loops are used to execute a block of code repeatedly. There are two main types of
loops: definite and indefinite.
Definite Loops
Also known as counted loops, execute a predetermined number of times.
The number of iterations is known before the loop starts.
Typically implemented using for loops.
Ideal for iterating over a sequence (list, tuple, string) or a range of numbers.
Python
# Example of a definite loop using for loop
for i in range(5):
print(i) # Output: 0, 1, 2, 3, 4
Indefinite Loops
Execute until a specific condition is met.
The number of iterations is not known in advance.
Typically implemented using while loops.
Ideal for situations where the loop should continue until a certain condition becomes
false.
Python
# Example of an indefinite loop using a while loop
count = 0
while count < 5:
print(count) # Output: 0, 1, 2, 3, 4
count += 1
Infinite Loops
A special case of indefinite loops where the condition never becomes false.
The loop continues to execute indefinitely unless externally interrupted.
Can occur unintentionally due to errors in the loop condition or intentionally for tasks
like event handling.
Python
7
# Example of an infinite loop
while True:
print("This will print forever!")
# To break out of the loop, you would need a break statement or external intervention
Key Differences
Feature Definite Loops Indefinite Loops
In essence, definite loops are for iterating a known number of times, while indefinite loops are
for repeating until a condition is met. Infinite loops are a type of indefinite loop that runs
indefinitely.
LISTS:
In Python, a list is a built-in dynamic sized array (automatically grows and shrinks). We can store
all types of items (including another list) in a list. A list may contain mixed type of items, this is
possible because a list mainly stores references at contiguous locations and actual items maybe
stored at different locations.
List can contain duplicate items.
List in Python are Mutable. Hence, we can modify, replace or delete the items.
List are ordered. It maintain the order of elements based on how they are added.
Accessing items in List can be done directly using their position (index), starting from 0.
Example :
# Creating a Python list with different data types
a = [10, 20, "GfG", 40, True]
print(a)
8
print(a[2]) # "GfG"
print(a[3]) # 40
print(a[4]) # True
PYTHON LIST
Note: Lists Store References, Not Values
Each element in a list is not stored directly inside the list structure. Instead, the list stores
references (pointers) to the actual objects in memory. Example (from the image representation).
The list a itself is a container with references (addresses) to the actual values.
Python internally creates separate objects for 10, 20, "GfG", 40 and True, then stores
their memory addresses inside a.
This means that modifying an element doesn’t affect other elements but can affect the
referenced object if it is mutable
CREATING A LIST
Here are some common methods to create a list:
Using Square Brackets
# List of integers
a = [1, 2, 3, 4, 5]
# List of strings
b = ['apple', 'banana', 'cherry']
print(a)
print(b)
print(c)
9
Output
[1, 2, 3, 4, 5]
['apple', 'banana', 'cherry']
[1, 'hello', 3.14, True]
Using list() Constructor
We can also create a list by passing an iterable (like a string, tuple or another list)
to list() function.
# From a tuple
a = list((1, 2, 3, 'apple', 4.5))
print(a)
Output
[1, 2, 3, 'apple', 4.5]
Creating List with Repeated Elements
We can create a list with repeated elements using the multiplication operator.
# Create a list [2, 2, 2, 2, 2]
a = [2] * 5
print(a)
print(b)
Output
[2, 2, 2, 2, 2]
[0, 0, 0, 0, 0, 0, 0]
Accessing List Elements
Elements in a list can be accessed using indexing. Python indexes start at 0, so a[0] will access
the first element, while negative indexing allows us to access elements from the end of the list.
Like index -1 represents the last elements of list.
a = [10, 20, 30, 40, 50]
10
print(a[-1])
Output
10
50
# Inserting 5 at index 0
a.insert(0, 5)
print("After insert(0, 5):", a)
Output
After append(10): [10]
After insert(0, 5): [5, 10]
After extend([15, 20, 25]): [5, 10, 15, 20, 25]
Updating Elements into List
We can change the value of an element by accessing it using its index.
a = [10, 20, 30, 40, 50]
print(a)
11
Output
[10, 25, 30, 40, 50]
Removing Elements from List
We can remove elements from a list using:
remove(): Removes the first occurrence of an element.
pop(): Removes the element at a specific index or the last element if no index is
specified.
del statement: Deletes an element at a specified index.
a = [10, 20, 30, 40, 50]
Output
After remove(30): [10, 20, 40, 50]
Popped element: 20
After pop(1): [10, 40, 50]
After del a[0]: [40, 50]
ITERATING OVER LISTS
We can iterate the Lists easily by using a for loop or other iteration methods. Iterating over lists
is useful when we want to do some operation on each item or access specific items based on
certain conditions. Let's take an example to iterate over the list using for loop.
Using for Loop
a = ['apple', 'banana', 'cherry']
12
Output
apple
banana
cherry
To learn various other methods, please refer to iterating over lists.
Nested Lists in Python
A nested list is a list within another list, which is useful for representing matrices or tables. We
can access nested elements by chaining indexes.
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
Output
6
13