Python - Unit II
Python - Unit II
A program’s control flow is the order in which the program’s code executes.
1. Sequential
## This is a Sequential
statement a=20
b=10
c=a-b
print("Subtraction is : ",c)
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.
● Simple if
● if-else
n = 10
if n % 2 == 0:
n=5
if n % 2 == 0:
print("n is even")
else:
print("n is odd")
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")
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!")
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))
● while loops
● for loops
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:
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.
# An empty list
L = []
There is one more way to create a list based on existing list, called List comprehension.
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
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
'black'] print(L[-1])
# Prints black
print(L[-2])
# Prints yellow
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:
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 :
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']
# removed item
print(x)
# Prints green
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)
List Replication
The replication operator * repeats a list a given number of times.
L = ['red']
L = L * 3
print(L)
# Prints ['red', 'red', 'red']
Example
You can also loop through the list items by referring to their index
iterable.
>>> 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]
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
[10,99,30,40,50]
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.
Create a Tuple:
III B.Sc IT – B -- SKACAS Python Programming – Unit II Page 15
thistuple = ("apple", "banana", "cherry")
print(thistuple)
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
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)
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.
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)
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
duplicates. Dictionaries are written with curly brackets, and have keys and values:
Example
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(thisdict)
● Dictionary items are presented in key:value pairs, and can be referred to by using the key
name.