Python UNIT 2
Python UNIT 2
UNIT 2
Lokesh CK
DATA TYPE
<class 'int'>
PYTHON DATA TYPE
Data types are the classification or categorization of data items.
It represents the kind of value that tells what operations can be performed on a particular data. Since
everything is an object in Python programming, data types are actually c l a sse s and variables are instance
(object) of these classes.
1) Numeric
2) Sequence Type
3) Boolean
4) Set
5) Dictionary
DICTIONARY DATA TYPE
Python Dictionary is used to store the data in a key-value pair format. The dictionary is the data type in Python, which
can simulate the real-life data arrangement where some specific value exists for some particular key.
It is the mutable(Changeable) data-structure.
The dictionary is defined into element Keys and values.
• Keys must be a single element
• Value can be any type such as list, tuple, integer, etc.
In other words, we can say that a dictionary is the collection of key-value pairs where the value can be any Python
object.
In contrast, the keys are the immutable(Not Changeable) Python object, i.e., Numbers, string, or tuple.
Dictionaries are written with curly brackets, and have keys and values:
DUPLICATES NOT ALLOWED
Example
Duplicate values will overwrite existing values:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964,
"year": 2020
}
print(thisdict)
OUTPUT:
{'brand': 'Ford', 'model': 'Mustang', 'year': 2020}
DICTIONARY LENGTH
To determine how many items a dictionary has, use the len() function:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964,
"year": 2020
}
print(len(thisdict))
OUTPUT: 3
DICTIONARY ITEMS – DATA TYPES
The values in dictionary items can be of any data type:
Example
String, int, boolean, and list data types:
thisdict = {
"brand": "Ford",
"electric": False,
"year": 1964,
OUTPUT:
{'brand': 'Ford', 'electric': False, 'year': 1964, 'colors': ['red', 'white', 'blue']}
TYPE()
From Python's perspective, dictionaries are defined as objects with the data type 'dict’:
<class 'dict’>
EXAMPLE
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(type(thisdict)
OUTPUT:
<class 'dict'>
As of Python version 3.7, dictionaries are ordered.
Creating Dictionary:
In Python, a Dictionary can be created by multiple key value pairs enclosed with the curly {} braces, separated by
‘comma’ and each key is separated from its value by the colon (:).
Values in a DICTIONARY can be of any datatype and can be duplicated, whereas keys can’t be repeated and must be
immutable (Can’t Change).
Note – Dictionary keys are case sensitive, same name but different cases of Key will be treated distinctly.
EXAMPLES
Dict = {}
print("Empty Dictionary: ")
print(Dict)
OUTPUT:
Empty Dictionary: {}
❖Creating a Dictionary with Integer Keys
OUTPUT:
Dictionary with the use of Integer Keys:
{1: ‘Mushfique', 2:‘Shahood'}
❖Creating a Dictionary with Mixed keys
OUTPUT:
Dictionary with the use of Mixed Keys:
{'Name': ‘REVA’, 1: [1, 2, 3, 4], }
❖Creating a Dictionary with dict() method
OUTPUT:
Dictionary with the use of dict():
{1: ‘Mushfique', 2:‘Shahood'}
❖Creating a Dictionary with each item a s a Pair
OUTPUT:
Dictionary with each item a s a pair:
{1: ‘Mushfique', 2:‘Shahood'}
Accessing elements of Dictionary
In order to access the items of a dictionary refer to its key name. Key can be used inside square brackets. There is
also a method called get() that will also help in accessing the element from a dictionary.
The dictionary is a mutable data type, and its values can be updated by using the specific keys.
The value can be updated along with key Dict[key] = value.
The update() method is also used to update an existing value.
Note:
If the key-value already present in the dictionary, the value gets updated. Otherwise, the new keys added in the
dictionary.
EXAMPLE
Dict = {}
print("Empty Dictionary: ")
print(Dict)
# Adding elements to dictionary one at a time
Dict[0] = ’Sagar’
Dict[2] = ’Saurav’
Dict[3] = ’Aashish’
print("\nDictionary after adding 3 elements: ")
print(Dict)
Empty Dictionary: {}
print(type(Employee))
print("printing Employee data .... ")
print(Employee)
print("Deleting some of the employee data")
del Employee["Name"]
del Employee["Company"]
print("printing the modified information ")
print(Employee)
print("Deleting the dictionary: Employee");
del Employee
print("Lets try to print it again ");
print(Employee)
OUTPUT:
<class 'dict’>
printing Employee data ....
{'Name': ‘Sagar', 'Age’: 22, 'salary': 25000, 'Company': 'GOOGLE’}
EXAMPLE
# Creating a Dictionary
Dict = {1: ’Mushfique', 2: ’Shahood', 3: ’Python'}
# Deleting a key
# using pop() method
pop_ele = Dict.pop(3)
print(Dict)
OUTPUT:
{1: ‘Mushfique', 2: ‘Shahood'}
NOTE:
Python also provides a built-in methods popitem() and clear() method for
remove elements from the dictionary.
The popitem() removes the arbitrary element from a dictionary, whereas
the clear() method removes all elements to the whole dictionary.
BUILT-IN DICTIONARY FUNCTION
SN Function Description
1 cmp(dict1, dict2) It compares the items of both the dictionary and returns true if the
first dictionary values are greater than the second dictionary,
otherwise it returns false.
➢ They are basic examples of containers ,as they contain other values.
List
➢ List items are ordered, it means the items have a defined order and the order will not
change.
➢ List items are changeable which means we can add, change or remove items in a list
after it has been created. When we add new items to a list, the new items will be placed
at the end of the list. Ex: thislist = [“apple”, ”banana”, ”cherry”, ”mango”]
➢ List items are indexed, the first item has index [0] ,the second item has index
1 and so on…
3
Functions
1. Length – len()
To determine how many items are there in a list, we use len() function.
Ex: thislist = [“apple”, ”banana”, ”cherry”]
len(thislist)
2. Datatype – type()
To determine what is the datatype of the list, we use type() function.
Ex: thislist = [“apple”, ”banana”, ”cherry”]
type(thislist)
4
3. Insert – append()
This function is used to enter only a single element at a time and it accepts only one
argument. It inserts elements at the end of the list.
Ex: list=[]
list.append(1)
list.append(2)
list.append(3)
4. Insert – insert()
This function is used to insert an element at a desired position and it accepts two
arguments (position, value)
Ex: list4.insert(3,False)
5
5. Delete – remove()
This function is used to remove one element at a time and accepts only one argument.
It removes the first occurrence of the searched element. If the element doesn’t exist in
the list an error will occur.
Ex: list4.remove(False)
6. Delete – pop()
This function is used to remove one element at a time and accepts only one
argument. It removes the element present in the specified position and in return
displays the element deleted.
Ex: list4.pop(4)
6
➢ Negative indexing
Negative sequence indexes represent positions from end of the list.Negative indexing
means beginning from the end, -1 refers to the last element, -2 refers to the second last
element and so on…
Ex: list4[-1]
list4[-2]
➢ Slicing of a List
We use this operation to print a specific range of elements from the list.The operation is
performed with the use of a colon(:).
Ex: list_S= ['G','E','N','E','R','A','L’]
Sliced_list=list_S[3:6]
7
CONTROL STATEMENTS
• If
• If-Else
• If-elif-else
• Nested If-Else
• For
• Nested For
IF
• The if-else statement checks the condition and executes the ‘if ’ block of
code when the condition is True, and If the condition is False it skips the
‘if ’ block is skipped
• Syntax :
if condition:
statement 1
statement 2
IF
Program :
num1 , num2 , num3 = int(input("Enter 1st number : ")) , int(input("Enter
2nd number : ")) , int(input("Enter 3rd number : "))
if num2 >=
numm1:
num1 = num2
if num3 >= num1:
num1 = num3
print("Greatest Number is",num1)
IF-ELS E
• The if-else statement checks the condition and executes the ‘if ’ block of
code when the condition is True, and if the condition is False, it will
execute the else block of code.
• Syntax :
if condition:
statement 1
else:
statement 2
IF-ELS E
Program :
n , f = int(input("Enter Number to find ODD or EVEN : ")) , 0
if(f%2==0):
print(n,"is Even")
else:
print(n,"is Odd")
IF-ELIF-ELS E
• The if-elif-else condition statement h as an ‘elif’ keyword used to chain multiple condition one
after another. The if-elif-else is useful when you need to check multiple conditions.
• Syntax :
if condition-1:
statement 1
elif condition-2:
statement 2
elif condition-3:
statement 3
else:
statement
IF-ELS E
Program :
n = int(input("Enter Marks to find GRADE : "))
if n > 90:
print("Your Grade i s A1")
elif n > 70:
print("Your Grade i s B1")
elif n > 80:
print("Your Grade i s A2")
elif n > 60:
print("Your Grade i s B2")
elif n > 50:
print("Your Grade i s C1")
elif n > 40:
print("Your Grade i s C2")
elif n > 32:
print("Your Grade i s D")
elif n > 20:
print("Your Grade i s E1 (Fail)")
else:
NESTED IF-ELSE
• The Nested If-Else statement is an if statement inside another ‘if-else’ statement.
It is allowed in Python to put any number of if statements in another if statement.
• Syntax :
if conditon_outer:
if condition_inner:
statement of nested if
else:
statement of nested
Program :
year = int(input("Enter year to find leap year or not : "))
if(year%100):
if(year%4 == 0):
print("Leap Year")
else:
print("Not a Leap Year")
else:
if(year%400 == 0):
print("Leap Year")
else:
print("Not a Leap Year")
FOR LOOP
• A for loop is used for iterating over a sequence and iterables (like range,
list, a tuple, a dictionary, a set or a string).
• Syntax :
for i in range/sequence:
statement 1
statement 2
statement n
FOR LOOP
Program :
n , f = int(input("Enter Number to find PRIME or not : ")) , 0
for i in range(1,n+1):
if(n%i==0):
f+=1
if(f==2):
print(n,"is Prime")
else:
print(n,"is Not Prime")
NESTED FOR LOOP
Program :
rows = 5
for i in range(0, rows):
for j in range(0, i + 1):
print("*", end=' ')
print("\r")
Control Structure
:
1. Iterative Statements
• For loop
• While Loop
• Examples
2. Selection Statements
• If Statements
• If-Else Statements
• Elif Statements
ITERATION
1. While loop:
The while statement repeats a body of code as long as a
condition is true.
Syntax:
while test_expression:
Body of while
ITERATION
1. For Loop:
The for statement can be used to iterate over
the members of a collection, so long as the
collection is a sequence.
Syntax:
for iterator_var in sequence:
statements(s)
ITERATING OVER A LIST:
>>>print("List Iteration")
>>>l = [“Manikanta", “Pradhan"]
>>>for i in l:
…. print(i)
ITERATING OVER A TUPLE:
>>>print(“Tuple Iteration")
>>>t = (“Manikanta",“Pradhan“)
>>>for i in t:
…. print(i)
ITERATING OVER A STRING:
>>>print(“Tuple Iteration")
>>>s = “Manikanta Pradhan”
>>>for i in s:
…. print(i)
ITERATING OVER A DICTIONARY:
>>>print("\nDictionary Iteration")
>>>d = dict()
>>>d['xyz'] = 123
>>>d['abc'] = 345
>>>for i in d :
…. print("%s %d" %(i, d[i]))
SELECTION STATEMENTS
1. If-else Statement:
The if-else statement evaluates test
expression and will execute the body of
if only when the test condition is True.
If the condition is False, the body of
else is executed.
SELECTION STATEMENTS
->>>If-else-if statements:
The elif is short for else if. It allows us to check for multiple expressions.
If the condition for if is False, it checks the condition of the next elif block and so on.
If all the conditions are False, the body of else is executed.
Only one block a m o ng the several if...elif...else blocks is executed according to the
condition.
The if block ca n have only one else block. But it ca n have multiple elif blocks.
SELECTION STATEMENTS
1. Syntax:
if test expression:
Body of if
elif test expression:
Body of elif
else:
Body of else
CONTROL STRUCTURES
1. Break Statement:
The break statement terminates the loop
containing it. Control of the program flows
to the statement immediately after the body
of the loop.
CONTROL STRUCTURES
1. Continue Statement:
The continue statement is used to
skip the rest of the code inside a
loop for the current iteration only.
Loop does not terminate but continues with
the next iteration.
CONTROL STRUCTURES
1. P a s s Statement:
In Python programming, the p a s s statement is a null statement. The
difference between a comment and a p a s s statement in Python is that
while the interpreter ignores a comment entirely, p a s s is not ignored.
NESTED LOOP
Python programming language allows to use one loop inside another loop is called as
nested loop
BASIC SYNTAX
outer loop:
inner loop:
statements of inner loop
statements of outer loop
NESTED LOOP
• When a loop is nested inside another loop. The inner loop runs many times inside
the outer loop. Each iteration of the outer loop, the inner loop will be restarted.
• The inner loop must finish all its iterations before the outer loop can continue to
its next iteration.
➢ It is used to deal with multiple condition in program.
➢ These are typically used for working with two dimensions such as printing starts in
rows and columns.
NESTED LOOP
Loops can be nested in following ways
1. For loop:
for loop:
2. while loop:
while loop:
3. For loop:
while loop:
4. While loop:
for loop:
NESTED FOR LOOP
For loop
where it falls under the category of definite iteration.
Definite iteration means the number of repetitions is specified explicitly in advance.
Nested for loop
A nested for loop is a loop that occurs within another loop, structurally similar to
nested if statements.
NESTED FOR LOOP
Syntax
For iterating_var1 in sequence:
For iterating_var2 in sequence:
statements(s)
statements(s)
NESTED FOR LOOP
NESTED FOR LOOP
The program first encounters the outer loop, executing its first iteration. This first
iteration triggers the inner, nested loop, which then runs to completion.
Then the program returns back to the top of the outer loop, completing the second
iteration and again triggering the nested loop.
Again, the nested loop runs to completion, and the program returns back to the top of
the outer loop until the sequence is complete or a break or other statement disrupts
the process.
NESTED FOR LOOP
* columns
rows 1 2 3 4
**
*** 1 *
**** 2 * *
3 * * *
4 * * * *
1. num = int(input("enter the number of rows:"))
for i in range(1,num+1):
for j in range(1,i+1):
print("*", end=" ")
print()
WHILE NESTED LOOP
Python programming language allows the use of a while loop inside another while
loop, it is known as nested while loop in Python programming language
WHILE NESTED LOOP
Syntax
While expression1:
while expression2:
statements(s)
statements(s)
WHILE NESTED LOOP
WHILE NESTED LOOP
In the nested-while loop in Python, Two type of while statements are available:
Outer while loop.
Inner while loop
Initially, Outer loop test expression is evaluated only once.
When its return true, the flow of control jumps to the inner while loop. the inner while
loop executes to completion. However,
when the test expression is false, the flow of control comes out of inner while loop
and executes again from the outer while loop only once. This flow of control persists
until test expression of the outer loop is false.
NESTED WHILE LOOP
Thereafter, if test expression of the outer loop is false, the flow of control skips the
execution and goes to rest.
NESTED WHILE LOOP
0 1 2 3 4 5 7
* 0 *
* *
1
* * * * *
* * *
* * * * 2
* * * *
3
num = int(input("enter the number of rows :"))
row = 0
while row<num:
space = num-row-1
while space>0:
print(end=" ")
space = space-1
star = row+1
while star>0:
print("*",end=" ")
star= star-1
row = row+1
print()
INVERTED HOLLOW PATTERN
1 2 3 4 5
* * * * *
0
1 * *
2 * *
3 * *
4 *
count =0
for i in range(5,0,-1):
j=1
while(j<=i):
if(count == 0):
print("*",end="")
j+=1
count+=1
print()
Control statements
• BREAK
• CONTINUE
• PASS STATEMENTS
INTRODUCTION
print("The end")
Output
s
t
r
The end
2.
number=[10,20,30,0,5,0,30]
for n in number:
if n==0:
break
print('100/{}={}'.format(n,100/n))
Output
100/10=10.0
100/20=5.0
100/30=3.3333333333333335
format():
•The format() method formats the specified value(s) and insert them inside
the string's placeholder. The placeholder is defined using curly brackets: {}.
•The format() method returns the formatted string.
Syntax
string.format(value1, value2...)
•The placeholders can be identified using named indexes {price},
numbered indexes {0}, or even empty placeholders {}.
Example
1.print("my age is {}" .format(10))
2. print("my name is {} and my age is {}" .format(“Rani",20))
3.
cart=[10,20,30,500,40,50]
for item in cart:
if item>=500:
print("cant process this order")
break
print(item)
else:
print("All items processed...")
print("out of for loop..")
Output
10
20
30
cant process this order
out of for loop..
The continue Statement
Output
The Number is : 0
The Number is : 1
The Number is : 2
The Number is : 3
The Number is : 4
The Number is : 5
The Number is : 6
The Number is : 8
The Number is : 9
2.
cart=[10,20,30,500,40,50]
for item in cart:
if item>=500:
print("cant process this order")
continue
print(item)
else:
print("All items processed...")
print("out of for loop..")
Output
10
20
30
cant process this order
40
50
All items processed...
out of for loop..
3.
for i in range(4):
for j in range(4):
if j==2:
continue
print("The number is ",i,j);
Output
The number is 0 0
The number is 0 1
The number is 0 3
The number is 1 0
The number is 1 1
The number is 1 3
The number is 2 0
The number is 2 1
The number is 2 3
The number is 3 0
The number is 3 1
The number is 3 3
The pass Statement
Output
r
e
Pass executed v
a
THANK YOU