Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
74 views

Python - Unit II

This document discusses various Python control flow statements and data structures. It covers sequential, selection/decision, and repetition control statements including if, if-else, nested if, while and for loops. It also covers lists, tuples, sets and dictionaries. Specifically for lists, it discusses creating and accessing lists by index, nested lists, list methods and mutability.

Uploaded by

Prakash M
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
74 views

Python - Unit II

This document discusses various Python control flow statements and data structures. It covers sequential, selection/decision, and repetition control statements including if, if-else, nested if, while and for loops. It also covers lists, tuples, sets and dictionaries. Specifically for lists, it discusses creating and accessing lists by index, nested lists, list methods and mutability.

Uploaded by

Prakash M
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 23

CONTROL STATEMENTS

CONTROL STATEMENTS: Control Flow and Syntax – Indenting – if Statement – statements


and expressions- string operations- Boolean Expressions –while Loop – break and continue – for
Loop. LISTS: List-list slices – list methods – list loop – mutability – aliasing – cloning lists – list
parameters. TUPLES: Tuple assignment, tuple as return value –Sets – Dictionaries

Control Flow and Syntax

A program’s control flow is the order in which the program’s code executes.

The control flow of a Python program is regulated by conditional statements, loops,


and function calls.

Python has three types of control structures:

● Sequential - default mode


● Selection - used for decisions and branching
● Repetition - used for looping, i.e., repeating a piece of code multiple times.

1. Sequential

Sequential statements are a set of statements whose execution process happens in a


sequence. The problem with sequential statements is that if the logic has broken in any one
of the lines, then the complete source code execution will break.

## This is a Sequential
statement a=20
b=10
c=a-b
print("Subtraction is : ",c)

2. Selection/Decision control statements

In Python, the selection statements are also known as Decision control statements or
branching statements.

The selection statement allows a program to test several conditions and execute
instructions based on which condition is true.

Some Decision Control Statements are:

● Simple if
● if-else

III B.Sc IT – B -- SKACAS Python Programming – Unit II Page 1


● nested if
● if-elif-else

Simple if: If statements are control flow statements that help


us to run a particular code, but only when a certain
condition is met or satisfied. A simple if only has one
condition to check.

n = 10
if n % 2 == 0:

print("n is an even number")

if-else: The if-else statement evaluates the condition and will


execute the body of if if the test condition is True, but if
the condition is False, then the body of else is executed.

n=5

if n % 2 == 0:
print("n is even")
else:

print("n is odd")

nested if: Nested if statements are an


if statement inside another if
statement.

a=5
b = 10
c = 15
if a > b:
if a > c:
print("a value is big")
else:
print("c value is
big") elif b > c:
print("b value is
big") else:
III B.Sc IT – B -- SKACAS Python Programming – Unit II Page 2
print("c is big")

if-elif-else: The if-elif-else statement is used to


conditionally execute a statement or a block
of statements.

x = 15
y = 12
if x == y:
print("Both are
Equal") elif x > y:
print("x is greater than
y") else:
print("x is smaller than y")

Python Indentation
Indentation refers to the spaces at the beginning of a code line.
Where in other programming languages the indentation in code is for readability only,
the indentation in Python is very important.
Python uses indentation to indicate a block of code.
Example
if 5 > 2:
print("Five is greater than two!")
Python will give you an error if you skip the indentation:
Example
Syntax Error:
if 5 > 2:
print("Five is greater than two!")
The number of spaces is up to you as a programmer, but it has to be at least one.
Example
if 5 > 2:
print("Five is greater than two!")

III B.Sc IT – B -- SKACAS Python Programming – Unit II Page 3


if 5 > 2:
print("Five is greater than two!")

Python Booleans
Booleans represent one of two values: True or False.
Boolean Values
In programming you often need to know if an expression is True or False.
You can evaluate any expression in Python, and get one of two answers, True or False.
When you compare two values, the expression is evaluated and Python returns the Boolean
answer:
Example
print(10 > 9)
print(10 == 9)
print(10 < 9)
When you run a condition in an if statement, Python returns True or False:
Example
Print a message based on whether the condition is True or False:
a = 200
b = 33
if b > a:
print("b is greater than
a") else:
print("b is not greater than a")
Evaluate Values and Variables
The bool() function allows you to evaluate any value, and give you True or False in return,
Example
Evaluate a string and a number:
print(bool("Hello"))
print(bool(15))

Python While Loops


Python Loops

III B.Sc IT – B -- SKACAS Python Programming – Unit II Page 4


Python has two primitive loop commands:

● while loops
● for loops

The while Loop


With the while loop we can execute a set of statements as long as a condition is true.
Example
Print i as long as i is less than 6:
i=1
while i < 6:
print(i)
i += 1
The while loop requires relevant variables to be ready, in this example we need to define
an indexing variable, i, which we set to 1.

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

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)

III B.Sc IT – B -- SKACAS Python Programming – Unit II Page 5


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

Python For Loops


A for loop is used for iterating over a sequence (that is either a list, a tuple, a dictionary, a set,
or a string).
This is less like the for keyword in other programming languages, and works more like
an iterator method as found in other object-orientated programming languages.
With the for loop we can execute a set of statements, once for each item in a list, tuple, set etc.
Example
Print each fruit in a fruit list:
fruits = ["apple", "banana", "cherry"]
for x in fruits:
print(x)

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

Nested 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
Print each adjective for every fruit:

III B.Sc IT – B -- SKACAS Python Programming – Unit II Page 6


adj = ["red", "big", "tasty"]
fruits = ["apple", "banana", "cherry"]
for x in adj:
for y in fruits:
print(x, y)

List
A list is a sequence of values (similar to an array in other programming languages but more
versatile)
The values in a list are called items or sometimes elements.
The important properties of Python lists are as follows:
● Lists are ordered – Lists remember the order of items inserted.
● Accessed by index – Items in a list can be accessed using an index.
● Lists can contain any sort of object – It can be numbers, strings, tuples and even other lists.
● Lists are changeable (mutable) – You can change a list in-place, add new items, and delete or
update existing items.
Create a List
There are several ways to create a new list; the simplest is to enclose the values in square
brackets []

# A list of integers
L = [1, 2, 3]
# A list of strings
L = ['red', 'green', 'blue']
The items of a list don’t have to be the same type. The following list contains an integer, a
string,
a float, a complex number, and a boolean.

III B.Sc IT – B -- SKACAS Python Programming – Unit II Page 7


# A list of mixed datatypes
L = [ 1, 'abc', 1.23, (3+4j), True]
A list containing zero items is called an empty list and you can create one with emptybrackets
[]

# An empty list
L = []
There is one more way to create a list based on existing list, called List comprehension.

The list() Constructor

You can convert other data types to lists using Python’s list() constructor.
# Convert a string to a list
L = list('abc')
print(L)
# Prints ['a', 'b', 'c']

Nested List

A list can contain sublists, which in turn can


contain sublists themselves, and so on. This
is known as nested list.
You can use them to arrange data into hierarchical structures.
L = ['a', ['bb', ['ccc', 'ddd'], 'ee', 'ff'], 'g', 'h']
Access List Items by Index
You can think of a list as a relationship between indexes and values. This relationship is called
a mapping; each index maps to one of the values. The indexes for the values in a list are
illustrated as below:
Note that the first element of a list is always at index zero.

You can access individual items in a list using an index in square brackets.
L = ['red', 'green', 'blue', 'yellow', 'black']
print(L[0])
# Prints red
print(L[2])
# Prints blue

III B.Sc IT – B -- SKACAS Python Programming – Unit II Page 8


Negative List Indexing
You can access a list by negative indexing as well. Negative indexes count backward from the
end of the list. So, L[-1] refers to the last item, L[-2] is the second-last, and so on.

The negative indexes for the items in a list are


illustrated as below:

L = ['red', 'green', 'blue', 'yellow',

'black'] print(L[-1])
# Prints black

print(L[-2])
# Prints yellow

Access Nested List Items

Similarly, you can access individual items in a nested list using multiple indexes. The first index
determines which list to use, and the second indicates the value within that list.
The indexes for the items in a nested list are illustrated as below:

L = ['a', 'b', ['cc', 'dd', ['eee', 'fff']], 'g', 'h']

print(L[2][2])
# Prints ['eee', 'fff']

print(L[2][2][0])
# Prints eee

List Slicing
A segment of a list is called a slice and you can extract one by using a slice operator. A slice of
a list is also a list.

To access a range of items in a list, you need to slice a list. One way to do this is to use
the simple slicing operator :

III B.Sc IT – B -- SKACAS Python Programming – Unit II Page 9


The slice operator [n:m] returns the part of the list from the “n-th” item to the “m-th” item,
including the first but excluding the last.
L = ['a', 'b', 'c', 'd', 'e', 'f']

print(L[2:5])
# Prints ['c', 'd', 'e']

print(L[0:2])
# Prints ['a', 'b']

print(L[3:-1])
# Prints ['d', 'e']

List/Array Methods
Python has a set of built-in methods that you can use on lists/arrays.
Add items to a list
To add new values to a list, use append() method. This method adds items only to the end of
the list.
L = ['red', 'green', 'yellow']
L.append('blue')
print(L)
# Prints ['red', 'green', 'yellow', 'blue']
If you want to insert an item at a specific position in a list, use insert() method. Note that all of
the values in the list after the inserted value will be moved down one index.
L = ['red', 'green', 'yellow']
L.insert(1,'blue')
print(L)
# Prints ['red', 'blue', 'green', 'yellow']

III B.Sc IT – B -- SKACAS Python Programming – Unit II Page 10


Combine Lists
You can merge one list into another by using extend() method. It takes a list as an argument
and appends all of the elements.
L = ['red', 'green', 'yellow']
L.extend([1,2,3])
print(L)
# Prints ['red', 'green', 'yellow', 1, 2, 3]

Remove items from a list


There are several ways to remove items from a list.
Remove an Item by Index
If you know the index of the item you want, you can use pop() method. It modifies the list and
returns the removed item.
If no index is specified, pop() removes and returns the last item in the list.
L = ['red', 'green', 'blue']
x = L.pop(1)
print(L)
# Prints ['red', 'blue']

# removed item
print(x)
# Prints green

Remove an Item by Value


If you’re not sure where the item is in the list, use remove() method to delete it by value.

If you’re not sure where the item is in the list, use remove() method to delete it by value.
L = ['red', 'green', 'blue']
L.remove('red')
print(L)

III B.Sc IT – B -- SKACAS Python Programming – Unit II Page 11


# Prints ['green', 'blue']
But keep in mind that if more than one instance of the given item is present in the list, then this
method removes only the first instance.
L = ['red', 'green', 'blue', 'red']
L.remove('red')
print(L)
# Prints ['green', 'blue', 'red']

Remove Multiple Items


To remove more than one items, use the del keyword with a slice index.
L = ['red', 'green', 'blue', 'yellow', 'black']
del L[1:4]
print(L)
# Prints ['red', 'black']

Remove all Items


Use clear() method to remove all items from the list.
L = ['red', 'green', 'blue']
L.clear()
print(L)
# Prints []

List Replication
The replication operator * repeats a list a given number of times.
L = ['red']
L = L * 3
print(L)
# Prints ['red', 'red', 'red']

Find List Length


To find the number of items in a list, use len() method.

III B.Sc IT – B -- SKACAS Python Programming – Unit II Page 12


L = ['red', 'green', 'blue']
print(len(L))
# Prints 3
Check if item exists in a list
To determine whether a value is or isn’t in a list, you can use in and not in operators with
if statement.
# Check for presence
L = ['red', 'green', 'blue']
if 'red' in L:
print('yes')
# Check for absence
L = ['red', 'green', 'blue']
if 'yellow' not in L:
print('yes')
List loop
You can loop through the list items by using a for loop:

Example

Print all items in the list, one by one:


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

Loop Through the Index Numbers

You can also loop through the list items by referring to their index

number. Use the range() and len() functions to create a suitable

iterable.

Print all items by referring to their index number:


thislist = ["apple", "banana", "cherry"]
for i in range(len(thislist)):
III B.Sc IT – B -- SKACAS Python Programming – Unit II Page 13
Mutability
Mutability is the ability for certain types of data to be changed without entirely recreating
it. This is important for Python to run programs both quickly and efficiently.
The list is a data type that is mutable. Once a list has been
created: Elements can be modified.
Individual values can be replaced.
The order of elements can be changed.
Lists are also dynamic. Elements can be added and deleted from a list, allowing it to grow
or shrink:
>>> a = ['spam', 'egg', 'bacon', 'tomato', 'ham', 'lobster']
>>> a
['spam', 'egg', 'bacon', 'tomato',
'ham', 'lobster']

>>> a[2]
'bacon'
>>> a[2] = 10
>>> a
['spam', 'egg', 10, 'tomato', 'ham',
'lobster']
Aliasing and Cloning Lists
Giving a new name to an existing list is called 'aliasing'. The new name is called 'alias name'.
For example, take a list 'x' with 5 elements
as x = [10, 20, 30, 40, 50]
To provide a new name to this list, we can simply use assignment operator
as: y = x
In this case, we are having only one list of elements but with two different names 'x' and 'y'.
Here, 'x' is the original name and 'y' is the alias name for the same list. Hence, any modifications
done to 'x' will also modify 'y' and vice versa. Observe the following statements where an
element x[1] is modified with a new value.

x = [10,20,30,40,50]
y = x #x is aliased as y
print(x) will display [10,20,30,40,50]
print(y) will display
[10,20,30,40,50]

x[1] = 99 #modify 1st element in x


III B.Sc IT – B -- SKACAS Python Programming – Unit II Page 14
print(x) will display [10,99,30,40,50]
print(y) will display
[10,99,30,40,50]

Hence, if the programmer wants two independent lists, he should not go for aliasing. On the
other hand, he should use cloning or copying.
Obtaining exact copy of an existing object (or list) is called 'cloning'. To clone a list, we can take
help of the slicing operation as:
y = x[:] #x is cloned as y
When we clone a list like this, a separate copy of all the elements is stored into 'y'. The lists
'x' and 'y' are independent lists. Hence, any modifications to 'x' will not affect 'y' and vice
versa. Consider the following statements:
x = [10,20,30,40,50]

y = x[:] #x is cloned as y

print(x) will display [10,20,30,40,50]

print(y) will display

[10,20,30,40,50] x[1] = 99 #modify

1st element in x print(x) will display

[10,99,30,40,50]

print(y) will display [10,20,30,40,50]


TUPLES

Tuples are used to store multiple items in a single variable.

Tuple is one of 4 built-in data types in Python used to store collections of data, the other 3
are List, Set, and Dictionary, all with different qualities and usage.

A tuple is a collection which is ordered


and unchangeable.

Tuple items are ordered, unchangeable, and allow


duplicate values.

Tuples are written with round brackets.

Create a Tuple:
III B.Sc IT – B -- SKACAS Python Programming – Unit II Page 15
thistuple = ("apple", "banana", "cherry")
print(thistuple)

III B.Sc IT – B -- SKACAS Python Programming – Unit II Page 16


Tuple Assignment

Besides tuple assignment is a special feature in python. We also call this feature unpacking of
tuple.

The process of assigning values to a tuple is known as packing. While on the other hand, the
unpacking or tuple assignment is the process that assigns the values on the right-hand side to
the left-hand side variables.

Example

>>>tup1 = (8, 99, 90, 6.7)


>>>(roll no., english, maths, GPA) = tup1
>>>print(english)
99
>>>print(roll no.)
8
>>>print(GPA)
6.7
>>>print(maths)
90
Tuples as return values

A function can only return one value, but if the value is a tuple, the effect is the same as
returning multiple values. For example, if you want to divide two integers and compute the
quotient and remainder, it is inefficient to compute x//y and then x%y. It is better to compute
them both at the same time.

The built-in function divmod takes two arguments and returns a tuple of two values, the
quotient and remainder. You can store the result as a tuple:

>>> t = divmod(7, 3)
>>> t (2, 1)

Or use tuple assignment to store the elements separately:

>>> quot, rem = divmod(7, 3)


>>> quot

III B.Sc IT – B -- SKACAS Python Programming – Unit II Page 17


2
>>> rem 1

Here is an example of a function that returns a tuple:

def min_max(t):
return min(t), max(t)

max and min are built-in functions that find the largest and smallest elements of a
sequence. min_max computes both and returns a tuple of two values.

Python Sets
Python Set is a collection of items.
Python Set is Unordered
There is no order in which the items are stored in a Set. We cannot access items in a
Set based on index.
Python Set has Unique Items
Python Set can store only unique items. We cannot add an item that is already present in
the Set.
Python Set is Mutable
We can modify a Set. In other words, we can add items to a Set or remove items from a
Set.
Create Python Set
To create a Set in Python, use curly braces {} as shown in the following example.

set_1 = {item_1, item_2, item_3}

Place as many items as required inside curly braces and assign it to a variable.
Example
#create set using curly
braces set_1 = {2, 4, 6}
print(set_1)

III B.Sc IT – B -- SKACAS Python Programming – Unit II Page 18


#create set using set() builtin
function set_2 = set({'a', 'b', 'c'})
print(set_2)
Output
{2, 4, 6}
{'b', 'c', 'a'}
Access Items of Python Set
Python Set is an iterable. Therefore, we can access items in a Set using for loop or while loop.
Example
In the following program, we create a set with three items, and print items one at a time by
accessing them using for loop.
set_1 = {2, 4, 6}
for item in
set_1:
print(item)
Output
2
4
6

Add Items to Python Set


To add an item to a Python Set, call add() method on the set, and pass the item.
In the following program, we create an empty set, and add three items to it
using add() method.
set_1 = set()
set_1.add(2)
set_1.add(4)
set_1.add(6)
print(set_1)
Output:

III B.Sc IT – B -- SKACAS Python Programming – Unit II Page 19


{2, 4, 6}

III B.Sc IT – B -- SKACAS Python Programming – Unit II Page 20


Remove Items from Python Set
To remove an item from a Python Set, call remove() method on the set, and pass the item.
Example
In the following program, we create a set with three items, and delete two of them
using remove() method.
set_1 = set({2, 4, 6})
print(f'Set before removing: {set_1}')

set_1.remove(2)
set_1.remove(6)
print(f'Set after removing: {set_1}')
Output:
Set before removing: {2, 4,
6} Set after removing: {4}
Dictionary

Dictionaries are used to store data values in key:value pairs.

A dictionary is a collection which is ordered*, changeable and do not allow

duplicates. Dictionaries are written with curly brackets, and have keys and values:

Example

Create and print a dictionary:

thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(thisdict)

III B.Sc IT – B -- SKACAS Python Programming – Unit II Page 21


Dictionary Items
● Dictionary items are ordered, changeable, and does not allow duplicates.

● Dictionary items are presented in key:value pairs, and can be referred to by using the key
name.

● To determine how many items a dictionary has, use the len()


function: print(len(thisdict))
● The values in dictionary items can be of any data
type: Thisdict = {
"brand": "Ford",
"electric": False,
"year": 1964,
"colors":["red", "white", "blue"]
}
● You can access the items of a dictionary by referring to its key name, inside
square brackets:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = thisdict["model"]
● The keys() method will return a list of all the keys in the
dictionary. x = thisdict.keys()
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = car.keys()
print(x) #before the change
III B.Sc IT – B -- SKACAS Python Programming – Unit II Page 22
car["color"] = "white"
print(x) #after the change
Output :
dict_keys(['brand', 'model', 'year'])
dict_keys(['brand', 'model', 'year', 'color'])

III B.Sc IT – B -- SKACAS Python Programming – Unit II Page 23

You might also like