0% found this document useful (0 votes)
4 views13 pages

unit 2

Unit II of the Python programming course covers selection control using if statements, including if-else and nested if-else structures, as well as iterative control with while and for loops. It explains lists in Python, detailing their properties, creation, and manipulation methods such as adding, updating, and removing elements. The unit also distinguishes between definite and indefinite loops, including infinite loops, and introduces nested lists for representing complex data structures.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views13 pages

unit 2

Unit II of the Python programming course covers selection control using if statements, including if-else and nested if-else structures, as well as iterative control with while and for loops. It explains lists in Python, detailing their properties, creation, and manipulation methods such as adding, updating, and removing elements. The unit also distinguishes between definite and indefinite loops, including infinite loops, and introduces nested lists for representing complex data structures.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 13

UNIT-II NOTES

Course name: Python programming

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:

In Python, If-Else is a fundamental conditional statement used for decision-making in


programming. If...Else statement allows to execution of specific blocks of code depending on the
condition is True or False.

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

# Checking if i is greater than 15


if (i > 15):
print("10 is less than 15")

print("I am Not in if")

IF....ELSE STATEMENT

if...else statement is a control statement that helps in decision-making based on specific


conditions. When the if condition is False. If the condition in the if statement is not true, the else
block will be executed.
If....else Statement

1
Let's look at some examples of if-else statements.
Simple if-else
i = 20

# Checking if i is greater than 0


if (i > 0):
print("i is positive")
else:
print("i is 0 or Negative")

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

# Ternary conditional to check if number is positive or negative


res = "Positive" if a >= 0 else "Negative"
print(res)

Output
Negative

Logical Operators with If..Else

We can combine multiple conditions using logical operators such as and, or, and not.
age = 25
exp = 10

# Using '>' operator & 'and' with if-else


if age > 23 and exp > 8:
print("Eligible.")
else:
print("Not eligible.")

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")

# If none of the above conditions are true


else:
print("i is not present")

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.

ITERATIVE CONTROL IN PYTHON:

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.

INFINITE LOOPS- DEFINITE VS. INDEFINITE LOOPS :

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

Iterations Predetermined Not predetermined

Implementation for loops while loops

Exit Condition Based on sequence/range Based on a condition

Infinite Loops Not applicable Possible if condition never becomes false

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)

# Accessing elements using indexing


print(a[0]) # 10
print(a[1]) # 20

8
print(a[2]) # "GfG"
print(a[3]) # 40
print(a[4]) # True

# Checking types of elements


print(type(a[2])) # str
print(type(a[4])) # bool
Explanation:
 The list contains a mix of integers (10, 20, 40), a string ("GfG") and a boolean (True).
 The list is printed and individual elements are accessed using their indexes (starting from
0).
 type(a[2]) confirms "GfG" is a str.
 type(a[4]) confirms True is a bool.

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']

# Mixed data types


c = [1, 'hello', 3.14, True]

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

# Create a list [0, 0, 0, 0, 0, 0, 0]


b = [0] * 7

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]

# Access first element


print(a[0])

# Access last element

10
print(a[-1])

Output
10
50

ADDING ELEMENTS INTO LIST


We can add elements to a list using the following methods:
 append(): Adds an element at the end of the list.
 extend(): Adds multiple elements to the end of the list.
 insert(): Adds an element at a specific position.
# Initialize an empty list
a = []

# Adding 10 to end of list


a.append(10)
print("After append(10):", a)

# Inserting 5 at index 0
a.insert(0, 5)
print("After insert(0, 5):", a)

# Adding multiple elements [15, 20, 25] at the end


a.extend([15, 20, 25])
print("After extend([15, 20, 25]):", 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]

# Change the second element


a[1] = 25

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]

# Removes the first occurrence of 30


a.remove(30)
print("After remove(30):", a)

# Removes the element at index 1 (20)


popped_val = a.pop(1)
print("Popped element:", popped_val)
print("After pop(1):", a)

# Deletes the first element (10)


del a[0]
print("After del a[0]:", a)

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']

# Iterating over the list


for item in a:
print(item)

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]
]

# Access element at row 2, column 3


print(matrix[1][2])

Output
6

13

You might also like