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

Python Unit 1

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

Python Unit 1

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

UNIT-1

Python:
--> Python is a widely used general purpose high level programming language.

--> Python was introduced by "Guido van Rossum" in 1991. after that python org has taken care about
this language development.

What can we do:


--> Create server side applications (web applications).

--> Create software workfolws.

--> Connect with databases also. We can also able to make modifications to the database files.

--> used for handling Big data.

Features of Python:

There are many features in Python, some of which are discussed below –

1. Easy to code:
Python is a high-level programming language. Python is very easy to learn the language as compared to
other languages like C, C#, Javascript, Java, etc. It is very easy to code in python language and anybody
can learn python basics in a few hours or days. It is also a developer-friendly language.

2. Free and Open Source:


Python language is freely available at the official website and you can download it. Since it is open-
source, this means that source code is also available to the public. So you can download it as, use it as
well as share it.

3. Object-Oriented Language:
One of the key features of python is Object-Oriented programming. Python supports object-oriented
language and concepts of classes, objects encapsulation, etc.

4. GUI Programming Support:


Graphical User interfaces can be made using a module such as PyQt5, PyQt4, wxPython, or Tk in python.
PyQt5 is the most popular option for creating graphical apps with Python.

5. High-Level Language:
Python is a high-level language. When we write programs in python, we do not need to remember the
system architecture, nor do we need to manage the memory.

Dept Of CSE-CBIT Page 1


6. Extensible feature:
Python is a Extensible language. We can write us some Python code into C or C++ language and also we
can compile that code in C/C++ language.

7. Python is Portable language:


Python language is also a portable language. For example, if we have python code for windows and if we
want to run this code on other platforms such as Linux, Unix, and Mac then we do not need to change it,
we can run this code on any platform.

8. Python is Integrated language:


Python is also an Integrated language because we can easily integrated python with other languages like
c, c++, etc.

9. Interpreted Language:
Python is an Interpreted Language because Python code is executed line by line at a time. like other
languages C, C++, Java, etc. there is no need to compile python code this makes it easier to debug our
code. The source code of python is converted into an immediate form called bytecode.

10. Large Standard Library :


Python has a large standard library which provides a rich set of module and functions so you do not have
to write your own code for every single thing. There are many libraries present in python for such as
regular expressions, unit-testing, web browsers, etc.

11. Dynamically Typed Language:


Python is a dynamically-typed language. That means the type (for example- int, double, long, etc.) for a
variable is decided at run time not in advance because of this feature we don’t need to specify the type
of variable

Data Types in Python:


Python consist of data types like:

1) Integer

2) Float

3) String

 If you are storing a number to a variable then that variable belongs to integer data type.

EX: a=10;

 If you are storing a number with some fractional part (decimal number) to a variable belongs to
float data type.

Ex: a=10.25;

Dept Of CSE-CBIT Page 2


 If you are storing some text to the variable then that variable belongs to the string data type.

Ex: a=”hello”;

 If you wanted to know the type of variable we can use “type()” function.

Ex: type(a);

o/p: <class ‘int’>

NOTE:

 List, Tuple, Dictionary also considered as data types in python.

Operators:
--> Operator is nothing but a symbol which can be used for performing some operation.

--> In python there are so many kinds of operators.

1) Arithmetic operators

2) Comparison operators

3) Assignment operators

4) Logical operators

5) Bitwise operators

Arithematic operators:

--> These operators are used for performing arithematic operations.

+ --> addition

- --> subtraction

* --> Multiplication

/ --> divison

% --> Modulo divison

Dept Of CSE-CBIT Page 3


Ex:

>>> a=10; >>> e=a*b;

>>> b=5; >>> print(e)

o/p: 50

>>> c=a+b;

>>> print(c) >>> f=a/b;

o/p: 15 >>> print(f)

o/p: 2

>>> d=a-b;

>>> print(d); >>> g=a%b;

o/p: 5 >>> print(g)

o/p: 0

Comparisonal Operators:

 These operators are used for performing comparison between two operands. We also called
these as Relational operators.

< --> lessthan

> --> greaterthan

<= --> lesthan or equalto

>= -->greaterthan or equalto

== --> equalsto

Ex: first.py

a=5; b=5;

if(a==b):

print("a and B having equal values")

else:

print("a is bigger than B")

Dept Of CSE-CBIT Page 4


o/p: a and B having equal values

Assignment operators:

 These operators are used for assigning something(either we can assign a value or a variable) to
the variable.
 The following are the Assignment operators.

= --> Aissgnment operator

+= --> Addition assignment operator

-= --> Subtraction assignment

/= --> Divison assignment

%= --> Modulo divison assignment

Ex: second.py

a=10

b=5

a+=b (in this line we are performing addition of a&b and the result we are assigning to a)

print(a)

o/p: 15

Logical operators:

--> These are used for performing Logical operations.

--> There are 2 logical operators.

Those are 1) and

2) or

--> When we are using and operator these the statement will execute when the both conditions are
true. "a and b"

--> If anyone are not satisfying the condition then these operator won't work.

--> Or operator can gets work if anyone among the given conditions is true.

Dept Of CSE-CBIT Page 5


Ex: Third.py

a=15

if(a<20 or a>18): (from the given conditions a<20 is correct so if part is going to execute)

print( "TRUE")

else:

print("FALSE")

o/p: TRUE

Ex: four.py

a=15

if(a<20 and a>18): (from the given conditions a>18 is wrong so if part is not executing)

print( "TRUE")

else:

print("FALSE")

o/p: False

Bitwise operators:

--> These operators perform the operation on bits of the given data.

--> There are 4 bitwise operators

a) & -> bitwise and

b) | -> bitwise or

c) << -> left shift

d) >> -> right shift

a) & -> bitwise and: When both bits have same value then only it will execute. otherwise it won’t.

Dept Of CSE-CBIT Page 6


A B A&B
T T T
T F F
F T F
F F F

b) | -> bitwise or: Among the both operands if anyone will be true then it returns true value.

A B A|B
T T T
T F T
F T T
F F F

c) << Left shift operator:

 This operator can perform shifting the left operand bits towards the left side for the given no of
times in the right operand.
 you can place 0's at right side.

Ex: 1) a= 011000

a<<2

result: 11000

2) a=1010

a<<3

result: 1010000

3) a=11100

a<<4

result: 111000000

Dept Of CSE-CBIT Page 7


d) >> (Right shift operator):

 In rightshift we are going to shift right side operand towards right side based on the value given
by the user.
 In a simple words how much shifts you want to apply those no of opearnds we just need to
remove.

Ex: 1) a=1010

a>>2

result: 10

2) a=1110

a>>1

result: 111

3) a= 00110

a>>2

result:001

Input and output


 The functions like input() and print() are widely used for standard input and output operations
respectively.

Python Output Using print() function


 We use the print() function to output data to the standard output device (screen). We can also
output data to a file, but this will be discussed later.
 An example of its use is given below.

EX:print('This sentence is output to the screen')

Output

This sentence is output to the screen

Another example is given below:

a=5
print('The value of a is', a)

Dept Of CSE-CBIT Page 8


Output

The value of a is 5

In the second print() statement, we can notice that space was added between the string and the
value of variable a. This is by default, but we can change it.

Output formatting

Sometimes we would like to format our output to make it look attractive. This can be done by
using the str.format() method. This method is visible to any string object.

>>> x = 5; y = 10
>>> print('The value of x is {} and y is {}'.format(x,y))
The value of x is 5 and y is 10

Here, the curly braces {} are used as placeholders. We can specify the order in which they are
printed by using numbers (tuple index).

print('I love {0} and {1}'.format('bread','butter'))


print('I love {1} and {0}'.format('bread','butter'))

Output

I love bread and butter


I love butter and bread

Python Input

To allow flexibility, we might want to take the input from the user. In Python, we have the
input()and raw_input() functions to allow this. The syntax for input() is:

1) raw_input([prompt]):

 Where prompt is the string we wish to display on the screen. It is optional.

>>> num = raw_input('Enter a number: ')


Enter a number: 10
>>> type(num)
o/p: <type 'str'>

Here, we can see that the entered value 10 is a string, not a number. To convert this into a
number we can use int() or float() functions.

>>> int('10')

Dept Of CSE-CBIT Page 9


2) input([prompt]):

 Where prompt is the string we wish to display on the screen. It is optional.


 input() can accept data with their own data types.

>>> num = input('Enter a number: ')


Enter a number: 10
>>> type(num)
o/p: <type 'int'>

>>> num = input('Enter a number: ')


Enter a number: 4.3
>>> type(num)
o/p: <type 'float'>

Control Structures:
--> Control structure is a block of code where decisions can be taken to perform certain actions.

--> There are 3 types of statements available control structures:

1) Selection statements:

--> These statements are used for selecting(taking the decision) what operation need to
perform.

--> Also called as Decision statements.

--> There are 3 selection statements:

a) if :

--> This statement is used for checking whether the given condition is true or not.

--> if the condition true then only it will perform the operation.

--> if the condition is false then it won't execute.

synatx:

if(condition):

block of code;

Dept Of CSE-CBIT Page 10


Ex:

a=15

b=7

if(a>b):

print("a is bigger than b")

if(b>a):

print("b is bigger than a")

o/p: a is bigger than b

b) if-else:

--> This also used for checking whether the given condition is true or not.

--> If the given condition is true then "if" block is going to execute.

--> If the given condition is false then "else" block is going to execute.

synatx:

if(condition):
block of code;
else:
block of code;

Ex:

a=01
b=7
if(a>b):
print("a is bigger than b")
else:
print("b is bigger than a")

o/p: b is bigger than a

c) Switch:

Dept Of CSE-CBIT Page 11


--> Switch allows us to select one option among the multiple options.

--> To implement switch statement we need to use the keyowrd called "switcher"

syntax:

switcher=

1: choice1
2: choice2
3: choice3
4: choice4
}

Ex:

def week(i): // creating a function

switcher={ // creating switch statement

1:'Sunday',
2:'Monday',
3:'Tuesday',
4:'Wednesday',
5:'Thursday',
6:'Friday',
7:'Saturday'
}

return switcher.get(i,"Invalid day of week") // giving the function output

choice=int(input("Enter a number between 1-7 to get the day to printed:"))


print(week(choice)) // we are getting final output for the given i/p

o/p: Enter a number between 1-7 to get the day to printed:6

Friday

Dept Of CSE-CBIT Page 12


2) Iteration statements:

--> These statements are used for performing some task repeatedly for "n" number of times.

--> Also called as loops.

--> There are 3 iteration statement:

a) for

b) while

c) do-while

a) for loop:

--> This can be used for performing some task repeatedly.

--> Until the given condition gets satisfy.

syntax:

for i in condition:

block of statements;

Ex:1) Ex:2)

for i in 'banana': a='hello'

print(i) for i in range(1):

o/p: re=a*2;

b print(re)
a
n o/p: hellohello
a
n
a

Dept Of CSE-CBIT Page 13


2) While loop:

--> This also perform some task repeatedly.

--> Until the given condition will become false.

syntax:

while condition:

block of statements;

Ex:1)

i=1 o/p:

while i<4: 1
2
print(i) 3

i=i+1;

3) do-while:

--> First perform the action then it will checks the condition.

syntax:

while True:

block of statements;

Ex:

i=1

while True: o/p:

print(i) 1
2
i=i+1 3
4
if(i==5):

break

Dept Of CSE-CBIT Page 14


3) control statements:

--> These statements are used for controlling the flow of execution.

--> There 3 control statements:

a) break

b) continue

c) pass

1) break:

--> This statement can be used for stop the execution.

synatax: break

Ex:

for i in range(1,10):

print(i)

if(i==5):

break

o/p:

1
2
3
4
5

2) continue:

--> This statement can just skip the execution at particular point.

--> And continues for next iterations.

syntax: continue

Ex:

Dept Of CSE-CBIT Page 15


for i in range(1,10):

if(i==5): //at 5 execution is skipping

continue

print(i)

o/p:

1
2
3
4
6
7
8
9

3) pass:

--> Just flow of execution can be done normally.

--> if you dont have any code to write inside of any condition or loop then we can place this
"pass" statement.

syntax: pass

Ex:1)

for i in range(1,10):

print(i)

if(i==5): //empty block i.e., nothing action to perform

o/p won't get for this type of empty blocks. To avoid this type of problems we are using pass.

Dept Of CSE-CBIT Page 16


Ex:2) o/p:

for i in range(1,10): 1
2
print(i) 3
4
if(i==5): 5
6
pass 7
8
9

Strings:

--> String is a collection of characters.

--> Characters may be alphabets, digits, symbols.

--> In python strings are immutable. i.e., we can't able to make modifications to the string.

--> To create a sting first we need to take a variable to that variable we need to assign the value
within either single quotes or double quotes.

Ex: 1) string1="Hello"

2) string2='hi'

--> stirng index value starts from '0'

Basic operations on string:

1) how to access characters of a string?

--> To access string characters we just need to give the string name and within the[position].

Ex: string1="Hello world"

a) string1[3] b) string1[7]

o/p: 'l' o/p: 'o'

Dept Of CSE-CBIT Page 17


Note: Even spaces also consider as a character.

--> If you want to access set of characters from the string then you need to specify the starting
index position and ending index position by placing : between the values.

This can be called as slicing.

c) string1[3:7] d) string1[2:9]

o/p: 'lo w' o/p: 'llo wor'

--> If you want to access the last character of the string.

e) string1[-1]

o/p: 'd'

--> if you want to access the string (print the string) in reverse order.

f) string1[::-1]

o/p: 'dlrow olleH'

2) How to update the string?

string2="Welcome to my world"

--> If you want to update some content the string that should not possible the reason is strings
are immuatable.

--> If you want to update entire string(replacing with new string) then we need to assign the
new string to the old string name.

Ex: string2="this is Python String update"

3) How to Delete the string?

--> If you want to delete some part of the string that should not possible the reason is strings
are immutable.

--> But we can able to delete entire string by using "del" keyowrd.

syntax: del stringname

Ex: del string2

Dept Of CSE-CBIT Page 18


--> Along with this string object providing some methods to us:

a) concatination:(+)

--> This one can be used for adding of two strings.

Ex: string1="Hello"

string2="Welcome"

string3= string1+string2

print(string3)

o/p: HelloWelcome

b) multiply(*):

--> This can be used for multiply the string i.e., if you want to print the string for "n" times then
we need to use this operator.

syntax: string*n

Ex: print(string1*2)

o/p: HelloHello

String Testing Methods:

--> Python provides 6 string testing methods. Those are:

1) isaplha():

--> This method can be used for checking whether the given string only consist of alphabets or
not.

--> If only alphabets are there it will return the value "True" otherwise "False".

syntax: stringname.isaplpha()

Dept Of CSE-CBIT Page 19


Ex:1) Ex:2)

string1="Hello" string2="Hello@123"

string1.isaplha() string2.isalpha()

o/p: True o/p: false

2) isalnum():

--> This methods can checks whether the given string consist of alphabet and numbers or not.

--> Then only it will return the value true otherwise it will return false.

syntax: stringname.isalnum()

Ex:1) string3="Hello123" Ex:2) string5="Hello@"

string3.isalnum() string5.isalnum()

o/p: True. o/p: False

3) islower():

--> This method is used for checking whether the given string consist of lowercase characters
only or not.

--> If it having only lower case characters then it will return the value "True" or it will return
"False".

syntax: stringname.islower()

Ex:1) string6="Hello" Ex:2) string7="hi"

string6.islower() string7.islower()

o/p: False o/p: True.

Dept Of CSE-CBIT Page 20


4) isupper():

--> This method can be used for checking whether the given string consist of uppercase letters
only or not.

--> If it is having only uppercase then it will return the value "True" or it will return the value
"False"

syntax: stringname.isupper()

Ex:1) string8="HellO" Ex:2) string9="Hello"

string8.isupper() string9.isupper()

o/p: True o/p: False

5) isspace():

--> This method can be used for checking whether the given string consist of only spaces or not.

--> If it is having only spaces then it will return the value "True" or it will return the value "False"

syntax: stringname.isspace()

Ex:1) string10="Hello Welcome" Ex:2) string11=" "

string10.isspace() string11.isspace()

o/p: False o/p: True.

6) isdigit():

--> This method is used for checking whether the string consist of only digits or not.

--> If it is having only digits then it will return the value "True" or it will return the value "False"

syntax: stringname.isdigit()

Ex:1) string12="Hello123" Ex:2) string13="789"

string12.isdigit() string13.isdigit()

o/p: False o/p: True

Dept Of CSE-CBIT Page 21


Lists
 Python offers a range of compound data types often referred to as sequences. List is one of the
most frequently used and very versatile data types used in python.
 A list is a sequence of values. The values in a list are called elements or sometimes items.
 Lists are mutable.

How to create a list?

 A List is created by placing all items inside the SQUARE BRACKETS “[ ]” separated by commas.
 It can have any number of items and they may be of different data types.

Ex: 1) my_list = [] # empty list

Ex: 2) my_list = [1, 2, 3] # list of integers

Ex: 3) my_list = [1, "Hello", 3.4] # list with mixed data types

 A list can also have another list as an item. This is called a nested list.
Ex: my_list = ["mouse", [8, 4, 6], ['a']] # nested list

Access List Elements:


 We can use the index operator [] to access an item in a list. In Python, indices start at 0. So, if a list
having 5 elements will have an index from 0 to 4.

Ex: my_list = ['p', 'r', 'o', 'b', 'e']

1) print(my_list[0])
Output: p

2) print(my_list[2])
Output: o

3) print(my_list[4])
Output: e

 Nested lists are accessed using nested indexing.

Dept Of CSE-CBIT Page 22


Ex: n_list=["Happy",[2,0,1,5]]
1) print(n_list[0][1]) Output: a

2) print(n_list[1][3]) Output: 5

Negative Indexing:

 Python allows negative indexing for its sequences.


 The index of -1 refers to the last item, -2 to the second last item and so on.

Ex: my_list = ['p','r','o','b','e']

1) print(my_list[-1])
Output: e
2) print(my_list[-5])
Output: p

How to slice lists in Python?

 We can access a range of items in a list by using the slicing operator “:” (colon).

Ex: my_list = ['p','r','o','g','r','a','m','i','z']

1) print(my_list[2:5])

Output: ['o', 'g', 'r']

2) print(my_list[:-5])

Output: ['p', 'r', 'o', 'g']

3) print(my_list[5:])

Dept Of CSE-CBIT Page 23


Output: ['a', 'm', 'i', 'z']

4) print(my_list[:])

Output: ['p', 'r', 'o', 'g', 'r', 'a', 'm', 'i', 'z']

Add/Change List Elements:

 Lists are mutable, meaning their elements can be changed.


 We can use the assignment operator “=” to change an item or a range of items.

Ex: odd = [2, 4, 6, 8]

1) odd[0] = 1

print(odd)

Output: [1, 4, 6, 8]

2) odd[1:4] = [3, 5, 7]

print(odd)

Output: [1, 3, 5, 7]

Delete List Elements:

 We can delete one or more items from a list using the “del” keyword.
 It can even delete the list entirely.

Ex: my_list=['p', 'r', ’o’, 'b', 'l', 'e', 'm']

1) del my_list[1:5]
print(my_list)

Output: ['p', ‘e’, 'm']

2) del my_list
print(my_list)

Output: Traceback (most recent call last):

File "<string>", line 18, in <module>

Dept Of CSE-CBIT Page 24


NameError: name 'my_list' is not defined

List Methods:

Python List providing us the following methods to work with lists.

1) append():
 Adds its argument as a single element to the end of a list. The length of the list
increases by one.

Ex: odd = [1, 3, 5]

1) odd.append(7)

print(odd)

Output: [1 , 3 , 5 , 7 ]

2) list2=[9,11,13]
odd.append(list2)
print(odd)

Output: [1 , 3 , 5 , 7 ,[9 , 11 , 13]]

2) extend():
 extend() can be used for adding each element to the list and extending the list. The
length of the list increases by number of elements in it’s argument.

Ex: odd = [1, 3, 5]

list2=[7 , 9, 11]

odd.extend(list2)

print(odd)

Output: [1 , 3 , 5 , 7, 9 , 11 ]

3) insert():
 insert() used for inserting items at specified location of the list.

Dept Of CSE-CBIT Page 25


Ex: odd = [1, 3, 5]

odd.insert(1,7)

print(odd)

Output: [1, 7, 3, 5]

4) remove():
 remove() can be used for removing the specified item from the list.

Ex: odd = [1, 3, 5, 7]

odd.remove(3)

print(odd)

Output: [1, 5, 7]

5) pop():
 pop() can be used for removing the last item from the lsit.

Ex: odd = [1, 3, 5, 7]

odd.pop()

print(odd)

Output: [1, 3, 5]

Tuples

 A Tuple is a collection of Python objects separated by commas. A tuple in Python is similar to


a list. The difference between the two is that we cannot change the elements of a tuple once
it is assigned whereas we can change the elements of a list i.e., Tuples are immutable.

Creating Tuples:

 A tuple is created by placing all the items (elements) inside parentheses (), separated by
commas.
 A tuple can have any number of items and they may be of different types (integer, float,
list, string, etc.).

Dept Of CSE-CBIT Page 26


Ex:

1) my_tuple= ()
print(my_tuple)

Output: ()

2) my_tuple= (1,2,3)
print(my_tuple)

Output: (1,2,3)

3) my_tuple(1,”Hello”,3.4)
print(my_tuple)

Output: (1,”Hello”,3.4)

Access Tuple Elements:

There are various ways in which we can access the elements of a tuple.

Indexing

 We can use the index operator [] to access an item in a tuple, where the index starts from 0.
 Trying to access an index outside of the tuple index range(6,7,... in this example) will raise
an IndexError.

Ex: my_tuple = ('p', 'r', 'o', 'b', 'e')

1) print(my_tuple[0])
Output: p

2) print(my_tuple[2])
Output: o

3) print(my_tuple[4])
Output: e

Dept Of CSE-CBIT Page 27


Negative Indexing

 Python allows negative indexing for its sequences.


 The index of -1 refers to the last item, -2 to the second last item and so on.

Ex: my_tuple = ('p', 'r', 'o', 'b', 'e')

1) print(my_tuple[-1])
Output: e

2) print(my_tuple[-2])
Output: b

Slicing
 We can access a range of items in a list by using the slicing operator “:” (colon).

Ex: my_tuple = ['p','r','o','g','r','a','m','i','z']

1) print(my_tuple[2:5])

Output: ['o', 'g', 'r']

2) print(my_tuple[:-5])

Output: ['p', 'r', 'o', 'g']

Deleting a Tuple:
 We cannot delete or remove items from a tuple because tuples are immutable.
 But we can able to remove (delete) entire tuple.

Ex: del my_tuple

Tuple Methods:
Tuples providing us the following methods:

1) count():
 This method is used for returning how many times that particular element has occurred in
the tuple.

Ex: my_tuple=( ‘ a ’, ‘ p ‘, ‘ p’, ‘ l ‘, ‘ e ‘ )

Dept Of CSE-CBIT Page 28


print(my_tuple.count( ‘ p ’ ))

Output: 2

2) Index():
 This method is used for knowing the position of particular element in the tuple.

Ex: my_tuple=( ‘ a ’, ‘ p ‘, ‘ p’, ‘ l ‘, ‘ e ‘ )

print(my_tuple.index( ‘ p ’ ))

Output: 1

Dictionary

 Python Dictionary is used to store the data in a key-value pair format.


 Dictionaries are mutable.
 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 Dictionaries “key” are immutable and “value” is mutable.

Creating Python Dictionary:


 Creating a dictionary is as simple as placing items inside “curly braces” {} separated by commas.
 An item has a key and a corresponding value that is expressed as a pair (key: value).

Ex:

1) Dict = {"Name": "Tom", "Age": 22}

In the above dictionary Dict, The keys Name and Age are the string that is an immutable object.

2) # Creating an empty Dictionary


Dict = {}
print("Empty Dictionary: ")
print(Dict)

Output: {}

Dept Of CSE-CBIT Page 29


Accessing the dictionary values:
 The values can be accessed in the dictionary by using the keys.
 The dictionary values can be accessed in the following way.

EX: Employee = {"Name": "John", "Age": 29, "salary":25000,"Company":"GOOGLE"}

1) print(Employee*‘Name’+)

Output: John

2) print(Employee*‘salary’+)

Output: 25000

Adding dictionary values:

 The dictionary values can be updated by using the specific keys.


 The value can be updated along with key Dict[key] = value.

EX: Employee = {"Name": "John", "Age": 29, "salary":25000,"Company":"GOOGLE"}

1) Employee*“Name”+=”Sreenu”
print(Employee)

Output: {'Salary': 25000, 'Company': 'Google', 'Name': 'Sreenu'}

Deleting dictionary items:


 The items of the dictionary can be deleted by using the “del” keyword.

EX: Employee = {"Name": "John", "Age": 29, "salary":25000,"Company":"GOOGLE"}

1) del Employee*“Name”+
print(Employee)

Output: {'Salary': 25000, 'Company': 'Google'}

Dept Of CSE-CBIT Page 30


Dictionary Methods:

 Python Dictionaries having the following methods.

1) Clear():
o This method is used for Remove all items from the dictionary.
EX: Employee = {"Name": "John", "Age": 29, "salary":25000,"Company":"GOOGLE"}
Employee.clear()
print(Employee)
Output: {}

2) Items():
o This method returns all the items of the dictionary.

EX: Employee = {"Name": "John", "Age": 29, "salary":25000,"Company":"GOOGLE"}

print(Employee.items())
Output: [('Salary', 25000), ('Company', 'Google'), ('Name', 'JHON')]

3) keys():
o This method is used for return the all keys of the dictionary.
EX: Employee = {"Name": "John", "Age": 29, "salary":25000,"Company":"GOOGLE"}

print(Employee.keys())

Output: ['Salary', 'Company', 'Name']

4) pop():
o This method is used for removing a item form the dictionary which “key” has passed as
argument.
EX: Employee = {"Name": "John", "Age": 29, "salary":25000,"Company":"GOOGLE"}

Employee.pop(‘Salary’)
print(Employee)

Output: ,‘Name’: ‘John’, 'Company': 'Google'}

5) popitem():
o This method is used for removing an arbitrary item of the dictionary.

EX: Employee = {"Name": "John", "Age": 29, "salary":25000,"Company":"GOOGLE"}

Employee.popitem()
print(Employee)

Dept Of CSE-CBIT Page 31


Output: {'Salary': 25000, 'Company': 'Google'}

6) values():
o This method is used for printing all the values of the dictionary.

EX: Employee = {"Name": "John", "Age": 29, "salary":25000,"Company":"GOOGLE"}


print(Employee.values())

Output: [25000, 29, 'GOOGLE', 'John']

Dept Of CSE-CBIT Page 32

You might also like