0% found this document useful (0 votes)
4 views

module 3

The document provides an overview of selection and iteration statements in Python, including if, if-else, elif, nested if statements, for loops, while loops, and their associated control statements like break and continue. It also covers sequence data types, particularly lists, detailing their properties, methods for manipulation, and examples of usage. The document serves as a comprehensive guide for understanding and implementing control flow and data structures in Python.

Uploaded by

Devi Pradeep
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

module 3

The document provides an overview of selection and iteration statements in Python, including if, if-else, elif, nested if statements, for loops, while loops, and their associated control statements like break and continue. It also covers sequence data types, particularly lists, detailing their properties, methods for manipulation, and examples of usage. The document serves as a comprehensive guide for understanding and implementing control flow and data structures in Python.

Uploaded by

Devi Pradeep
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 19

MODULE 3

Selection Statements
1. if Statement
The if statement in Python is used to make decisions based on conditions. It allows you to
execute a block of code only if a specified condition is true.
Syntax:
if condition:
# Code block to execute if condition is true
Example:
temperature = 30
if temperature > 25:
print("It's a hot day.")
Output

'It's a hot day.t day.

2. if-else Statement
The if-else statement in Python is a fundamental control structure that allows you to execute
specific blocks of code based on whether a condition is true or false.
How It Works
1. Condition Evaluation: The condition inside the if statement is evaluated.
2. Execution:
o If the condition is True, the code block following the if statement is executed.
o If the condition is False, the code block following the else statement is
executed.
Syntax:
if condition:
# Code block if condition is true
else:
# Code block if condition is false
Example:
temperature = 20
if temperature > 25:
print("It's a hot day.")
else:
print("It's a pleasant day.")
Output
It's a pleasant day.

3. elif Statement
The elif statement is used when you want to check multiple conditions. It is possible to have
multiple elif statements following an if.
Syntax:
if condition1:
# Code block if condition1 is true
elif condition2:
# Code block if condition2 is true
else:
# Code block if all conditions are false
Example:
temperature = 15
if temperature > 25:
print("It's a hot day.")
elif temperature > 15:
print("It's a warm day.")
else:
print("It's a cool day.")
Output
It's a cool day.

4. Nested if Statements
It is possible to nest if statements within each other to create more complex conditions.
Syntax
if condition1:
# Code block if condition1 is true
if condition2:
# Code block if condition2 is true
else:
# Code block if condition2 is false
else:
# Code block if condition1 is false
Example:
num = 10
if num > 0:
print("Positive number")
if num % 2 == 0:
print("Even number")
else:
print("Odd number")
else:
print("Negative number or zero")
Output
Positive number
Even number

Iteration Statements
1. for Loop
The for loop is used to iterate over a sequence (like a list, tuple, or string) or to execute a
block of code a specific number of times.
Syntax:
for variable in sequence:
# Code block to execute for each element
Example:
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)

2. 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:
for i in range(5): # Loops from 0 to 4
print(i)

Output
0
1
2
3
4
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):
for x in range(2, 6):
print(x)

output
2
3
4
5

You can also specify the start and step values:


for i in range(1, 10, 2): # Starts at 1, goes to 10, increments by 2
print(i)
Output:
1
3
5
7
9

For loop examples


1. Print each fruit in a fruit list:
fruits = ["apple", "banana", "cherry"]
for x in fruits:
print(x)
Output
apple
banana
cherry

2. Loop through the letters in the word "banana":


for x in "banana":
print(x)

Output
b
a
n
a
n
a
3. With the break statement we can stop the loop before it has looped
through all the items:

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


for x in fruits:
print(x)
if x == "banana":
break
Output
apple
banana

4.Exit the loop when x is "banana", but this time the break comes before the
print:

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


for x in fruits:
if x == "banana":
break
print(x)
Output
apple

5. With the continue statement we can stop the current iteration of the loop,
and continue with the next:

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


for x in fruits:
if x == "banana":
continue
print(x)
Output
apple
cherry

Else in For Loop


The else keyword in a for loop specifies a block of code to be executed when the loop is
finished:
Example
Print all numbers from 0 to 5, and print a message when the loop has ended:
for x in range(6):
print(x)
else:
print("Finally finished!")
Output
0
1
2
3
4
5
Finally finished!

The else block will NOT be executed if the loop is stopped by a break statement.
Example
Break the loop when x is 3, and see what happens with the else block:
for x in range(6):
if x == 3: break
print(x)
else:
print("Finally finished!")
Output
0
1
2

Nested for Loops


A nested loop is a loop inside a loop.
The "inner loop" will be executed one time for each iteration of the "outer loop":
Example 1
Print each adjective for every fruit:
adj = ["red", "big"]
fruits = ["apple", "banana"]

for x in adj:
for y in fruits:
print(x, y)

Output
red apple
red banana
big apple
big banana
Example 2
for x in range(3):
for y in range(3):
print(x, y)

Output
00
01
02
10
11
12
20
21
22

The pass Statement


for loops cannot be empty, but if you for some reason have a for loop with no content, put
in the pass statement to avoid getting an error.
Example
for x in [0, 1, 2]:
pass
Output
3. while Loop
A while loop continues to execute as long as a specified condition is true.
Syntax:
while condition:
# Code block to execute as long as condition is true
Example:
count = 1
while count < =5:
print(count)
count += 1 # Increment count to avoid infinite loop
Output
1
2
3
4
5

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
Output
1
2
3

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)

Output
1
2
4
5
6

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

Output
1
2
3
4
5
i is no longer less than 6

Nested While Loop


i=1
while i < 3:
j=1
while j<3:
print(i,j)
j+=1
i += 1
Output
11
12
21
22

4. Combining Selection with Iteration


You can combine selection statements within loops for more complex logic.
Example:
numbers = [1, -2, 3, -4, 5]
for num in numbers:
if num > 0:
print(f"{num} is positive")
elif num < 0:
print(f"{num} is negative")
else:
print("Zero")
Output
1 is positive
-2 is negative
3 is positive
-4 is negative
5 is positive

Sequence Datatypes in Python


Sequence data types allow multiple data values to be stored within a single structure.
1. LISTS
List is a collection of things, enclosed in [] and separated by commas.
Lists are used to store multiple items in a single variable.
Lists are one of 4 built-in data types in Python used to store collections of data, the
other 3 are Tuple, Set, and Dictionary, all with different qualities and usage.
Example
Create a List:

Properties of Lists
List items are ordered, changeable, and allow duplicate values.
List items are indexed, the first item has index [0], the second item has index [1] etc.
Ordered
When we say that lists are ordered, it means that the items have a defined order, and
that order will not change.
If you add new items to a list, the new items will be placed at the end of the list.
Changeable
The list is changeable, meaning that we can change, add, and remove items in a list
after it has been created.
Allow Duplicates
Since lists are indexed, lists can have items with the same value:
Example
Lists allow duplicate values:

List Length
To determine how many items a list has, use the len() function:

List Items - Data Types


List items can be of any data type:
Example: String, int and boolean data types:
A list can contain different data types:
Example
A list with strings, integers and boolean values:

type()
From Python's perspective, lists are defined as objects with the data type 'list':

The list() Constructor


It is also possible to use the list() constructor when creating a new list.
Example
Using the list() constructor to make a List:

Access Items
List items are indexed and you can access them by referring to the index number:
Example : Print the second item of the list:

Note: The first item has index 0.


Negative Indexing
Negative indexing means start from the end
-1 refers to the last item, -2 refers to the second last item etc.
Range of Indexes
You can specify a range of indexes by specifying where to start and where to end the
range.
When specifying a range, the return value will be a new list with the specified items.
Example
Return the third, fourth, and fifth item:

Note: The search will start at index 2 (included) and end at index 5 (not included).
Remember that the first item has index 0.
By leaving out the start value, the range will start at the first item:
Example
This example returns the items from the beginning to, but NOT including, "kiwi":

By leaving out the end value, the range will go on to the end of the list:
Example
This example returns the items from "cherry" to the end:

Range of Negative Indexes


Specify negative indexes if you want to start the search from the end of the list:
Example
This example returns the items from "orange" (-4) to, but NOT including "mango"
(-1)

Check if Item Exists


To determine if a specified item is present in a list use the in keyword:
Example
Check if "apple" is present in the list:

Change Item Value


To change the value of a specific item, refer to the index number:
Example
Change the second item:

Change a Range of Item Values


To change the value of items within a specific range, define a list with the new values,
and refer to the range of index numbers where you want to insert the new values:
Example
Change the values "banana" and "cherry" with the values "blackcurrant" and
"watermelon":

If you insert more items than you replace, the new items will be inserted where you
specified, and the remaining items will move accordingly:
Example
Change the second value by replacing it with two new values:
Note: The length of the list will change when the number of items inserted does not
match the number of items replaced.
If you insert less items than you replace, the new items will be inserted where you
specified, and the remaining items will move accordingly:
Example
Change the second and third value by replacing it with one value:

Insert Items
To insert a new list item, without replacing any of the existing values, we can use
the insert() method.
The insert() method inserts an item at the specified index:
Example
Insert "watermelon" as the third item:

Note: As a result of the example above, the list will now contain 4 items.

Python - Add List Items


Append Items
To add an item to the end of the list, use the append() method:
Example
Using the append() method to append an item:
Insert Items
To insert a list item at a specified index, use the insert() method.
The insert() method inserts an item at the specified index:
Example
Insert an item as the second position:

Note: As a result of the examples above, the lists will now contain 4 items.

Extend List
To append elements from another list to the current list, use the extend() method.
Example
Add the elements of tropical to thislist:

Remove Specified Item


The remove() method removes the specified item.
Example
Remove "banana":
thislist = ["apple", "banana", "cherry"]
thislist.remove("banana")
print(thislist)
OUTPUT
['apple', 'cherry']
If there are more than one item with the specified value, the remove() method
removes the first occurrence:
Example
Remove the first occurrence of "banana":
thislist = ["apple", "banana", "cherry", "banana", "kiwi"]
thislist.remove("banana")
print(thislist)
OUTPUT
['apple', 'cherry', 'banana', 'kiwi']

Remove Specified Index


The pop() method removes the specified index.
Example
Remove the second item:
thislist = ["apple", "banana", "cherry"]
thislist.pop(1)
print(thislist)
OUTPUT
['apple', 'cherry']
If you do not specify the index, the pop() method removes the last item.
Example
Remove the last item:
thislist = ["apple", "banana", "cherry"]
thislist.pop()
print(thislist)
OUTPUT
['apple', 'banana']
The del keyword also removes the specified index:
Example
Remove the first item:
thislist = ["apple", "banana", "cherry"]
del thislist[0]
print(thislist)
OUTPUT
['banana', 'cherry']
The del keyword can also delete the list completely.
Example
Delete the entire list:
thislist = ["apple", "banana", "cherry"]
del thislist
Clear the List
The clear() method empties the list.
The list still remains, but it has no content.
Example
Clear the list content:
thislist = ["apple", "banana", "cherry"]
thislist.clear()
print(thislist)
OUTPUT
[]

You might also like