0% found this document useful (0 votes)
3 views48 pages

Merged

The document provides an introduction to Python programming, highlighting its features such as ease of use, interpreted nature, and support for object-oriented programming. It also covers the history of Python, its applications across various domains, and important concepts like keywords, identifiers, variables, indentation, comments, and data types. Additionally, it explains numeric data types and the characteristics of integers and floating-point numbers.

Uploaded by

bhukansatyam69
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views48 pages

Merged

The document provides an introduction to Python programming, highlighting its features such as ease of use, interpreted nature, and support for object-oriented programming. It also covers the history of Python, its applications across various domains, and important concepts like keywords, identifiers, variables, indentation, comments, and data types. Additionally, it explains numeric data types and the characteristics of integers and floating-point numbers.

Uploaded by

bhukansatyam69
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 48

UNIT-I Introduction and Syntax of Python Program

 Features of Python: Total Marks - 08

Python provides lots of features that are listed below.

1. Easy to learn and Use:


- Python is very easy to learn language as compared to other language like c, c#, java script,
java etc.
- It is very easy to code in python language.
- It is developer-friendly language.
- Python is high level programming language.

2. Interpreted Language:
- Python is an interpreted language i.e. interpreter executes the code line by line at a time.
- This makes debugging easy.
- Python code is processed at runtime by the interpreter.
- You do not need to compile your program before executing it. This is similar to PERL and
PHP language.
- Interpreter generate the code which run on any platform that’s via Python is known as
Platform Independent programming language.

3. Free and Open Source:


- Python language is freely available at official website and you can download it without
purchasing any license copy.
- It is open source programing language, it means, its source code is also available to the
public.

4. Object Oriented Programming:


- Python supports object oriented language and concepts of classes , objects, inheritance,etc.
- This is one of the key feture of Python programming language.
- In this programming language, we are focusing on data rather than procedure.
- Here, we will provide the more security for the data.

5. Cross-platform and Portable language:


- Python language is portable programming language.
- It means, you can easily move python code from one machine to another machine.
- For example, if we have code of windows machine then we want to run this code on other
machine such as Linux, Unix, Mac OS then we can easily run it without changing any code.
- We can run Python code on any platform.

Python Programming by Mr. Vishal Jadhav Sir’s (VJTech Academy, contact us: +91-9730087674) 1
UNIT-I Introduction and Syntax of Python Program

6. Large Standard Library:


- Python has a large standard libraries.
- It provides rich set of modules and functions which help us to develop the Python program.
- There are many libraries present in python such as regular expressions, unit-testing, web
browsers etc.

7. Dynamically Typed Language:


- Python is dynamically-typed language.
- It means the type (for example- int, float, long etc) for a variable is decided at run time.
- Because of this feature we don’t need to specify the data type of variable.

8. Integrated Language:
- Python is an Integrated programming language because we can easily integrate python with
other language like c, c++ etc.

9. 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.

10. GUI Programming Support:


- Graphical Users interfaces(GUI) can be developed using a python module such as PyQt5,
PyQt4, wxPython or Tk in python.
- PyQt5 is the most popular option for creating graphical apps with Python.

11. Support Garbage Collection:


- Python deletes unwanted objects (built-in types or class instances) automatically to free the
memory space.
- The process by which Python periodically frees and reclaims blocks of memory that no
longer are in use is called Garbage Collection.

Python Programming by Mr. Vishal Jadhav Sir’s (VJTech Academy, contact us: +91-9730087674) 2
UNIT-I Introduction and Syntax of Python Program

 History of Python:
- Python laid its foundation in the late 1980s.
- The implementation of Python was started in the December 1989 by Guido Van Rossum at
Centrum Wiskunde & Informatica (CWI) in Netherland.
- In 1994, Python 1.0 was released with features like: lambda, map, filter, and reduce.
- Python 2.0 added new features like: list comprehensions, garbage collection system.
- On December 3, 2008, Python 3.0 (also called "Py3K") was released. It was designed to
rectify fundamental flaw of the language.
- ABC programming language is said to be the predecessor of Python language which was
capable of Exception Handling and interfacing with Amoeba Operating System.

 Applications of Python:

Python is known for its general purpose nature that makes it applicable in almost each domain
of software development. Python programming is widely used in Artificial Intelligence, Natural
Language Generation, Neural Networks and other advanced fields of Computer Science.

1) Web Applications.
2) Desktop GUI Applications
3) Software Development
4) Scientific and Numeric
5) Business Applications
6) Console Based Application
7) Audio or Video based Applications
8) 3D CAD Applications
9) Enterprise Applications
10) Applications for Images

Many large companies use the Python programming language include NASA, Google, YouTube,
BitTorrent, etc.

Python Programming by Mr. Vishal Jadhav Sir’s (VJTech Academy, contact us: +91-9730087674) 3
UNIT-I Introduction and Syntax of Python Program

 Python Keywords:
- Keywords are the reserved words in Python.
- We cannot use keyword as a variable name, function name or some other purpose.
- Each and every keywords has some special meaning.
- In Python, keywords are case sensitive.
- All the keywords should be written in lower case except True, False and None.
- The list of all the keywords are given below. This list can vary slightly in the course of time.

Keywords in Python

False class finally is return

None continue for lambda try

True def from nonlocal while

and del global not with

as elif if or yield

assert else import pass

break except in raise

Python Programming by Mr. Vishal Jadhav Sir’s (VJTech Academy, contact us: +91-9730087674) 4
UNIT-I Introduction and Syntax of Python Program

 Python Identifiers:
- An identifier is a name which given to class, functions, variables, etc.
- It helps to differentiate one entity from another.
- All user defined name which we use in Python code is known as Identifier. We use name for
the identification purpose.
- Following are the rules which we use while constructing the Identifier Name.
1. Identifiers name must start with a alphabets or the underscore(_) character.
2. It may combine with Numbers(0-9).
3. Identifiers name should not start with Numbers(0-9).
4. Keywords cannot be used as an Identifier name.
5. It does not allowed any white space between Identifiers name.
6. It does not allowed any special symbols except underscore in Identifiers name.
7. Identifiers names are case-sensitive (Eg. VJTECH, VJTech and vjtech are three different
variables).
8. Identifier name can be of any length.

Example:

#Valid identifier names:


vjtech
vj_tech
_vj_tech
vjTech
VJTECH
vjtech123

# Invalid identifier names:


2vjtech #begin with number 2
vj@tech #special symbol @ present
VJ Tech #white space used

Python Programming by Mr. Vishal Jadhav Sir’s (VJTech Academy, contact us: +91-9730087674) 5
UNIT-I Introduction and Syntax of Python Program

 Python Variables:
- Variable is an Identifier which can change value during the execution of program.
- Variable act as a container for storing the value.
- A variable is a named location used to store data in the memory.
- In python, there is no need of declaration of variables by using the data type.
- We can directly use the variable name for storing the value and its data type is decided
dynamically as per the stored value on it.
- Following are the rules which we use while constructing the variable Name.
1. Variable name must start with a alphabets or the underscore(_) character.
2. It may combine with Numbers(0-9).
3. Variable name should not start with Numbers(0-9).
4. Keywords cannot be used as an Variable name.
5. It does not allowed any white space between Variable name.
6. It does not allowed any special symbols except underscore in Variable name.
7. Variable name is case-sensitive (Eg. VJTECH, VJTech and vjtech are three different
variables).
8. Variable name can be of any length.

Example:

#Valid variable names:


vjtech = "Vishal Sir"
vj_tech = 123
_vj_tech = 34.56
vjTech = 3+5.6j
VJTECH = (10,20,30,40)
vjtech123= [12,4.5,67,89]

# Invalid variable names:


2vjtech = 123
vj#tech = "Vishal Sir"
VJ Tech = 678.99

Python Programming by Mr. Vishal Jadhav Sir’s (VJTech Academy, contact us: +91-9730087674) 6
UNIT-I Introduction and Syntax of Python Program

- Assigning a value to a Variable in Python: you can use the assignment operator (=) to assign
a value to a variable.
- Example 1: Declaring and assigning a value to a variable

Roll_No = 1010;
print("My Roll No:",Roll_No);

When you run the program, the output will be:

My Roll No:1010

- Example 2: Changing the value of variable

Roll_No = 1010;
print("My Roll No:",Roll_No);
Roll_No = 2020;
print("My Roll No:",Roll_No);

When you run the program, the output will be:

My Roll No:1010
My Roll No:2020

- Example 3: Assigning multiple values to multiple variables

a, b, c = 56, 3.2, "Hello";

print("Value of a=",a);
print("Value of b=",b);
print("Value of c=",c);

When you run the program, the output will be:

Value of a=56
Value of a=3.2
Value of a=Hello

- Example 4: If we want to assign same value to multiple variables.

a=b=c="Hello";
print("Value of a=",a);
print("Value of b=",b);
print("Value of c=",c);

Python Programming by Mr. Vishal Jadhav Sir’s (VJTech Academy, contact us: +91-9730087674) 7
UNIT-I Introduction and Syntax of Python Program

 Python Indentation:
- Most of the programming languages like C, C++, Java use curly brackets { } to define a block
of code. Python uses indentation.
- A code block (body of a function, loop etc.) starts with indentation and ends with the first
unindented line.
- The amount of indentation is up to you, but it must be consistent throughout that block.
- If we use indentation in Python then the code look neat and clean.
- Generally four whitespaces are used for indentation or we can use single Tab.
- Example:

for i in range(1,11):
if i == 5:
break
print(i)

Python Programming by Mr. Vishal Jadhav Sir’s (VJTech Academy, contact us: +91-9730087674) 8
UNIT-I Introduction and Syntax of Python Program

 Python Comments:
- Comments are very important while writing a program.
- It describes what's going on inside a program so that a person looking at the source code
can understand the code easily.
- You might forget the key details of the program you just wrote in a mon th's time. So taking
time to explain these concepts in form of comments is always helpful.
- Comment is a part of documentation which helps us to give more detail information about
the code.
- Python Interpreter ignores the comments, it will not run.
- There are two types of comments present in Python.
1. Single line comments
2. Multi-line comments

Single line comments:

- In Python, we use the hash (#) symbol to write a single line comment.
- Single line comment begin with # symbol and end with the end of line.
- We can cover multiple lines by using single line comment, for that you have to write #
symbol for beginning of each line.
- Example:

#This is Python Program which display Message.


#This program developed by VJTech Academy

print("Welcome to world of Python Language");

Multi-line Comments:

- In Python, multi-line comments begin with three times either single quotes (''') or double
quotes (""") and end with three times either single quotes (''') or double quotes (""").
- These triple quotes are generally used for multi-line strings.
- But they can be used as multi-line comment as well.
- Example:

"""This is Python Program which display Hellp Message.


This program developed by VJTech Academy """

print("Welcome to world of Python Language");

Python Programming by Mr. Vishal Jadhav Sir’s (VJTech Academy, contact us: +91-9730087674) 9
UNIT-I Introduction and Syntax of Python Program

 Data Types in Python:


- Every value in Python has a datatype.
- Variables can hold values of different data types.
- Python is a dynamically typed language hence we need not define the data type of the
variable while declaring it.
- The interpreter implicitly binds the value with its data type.
- We can check the data type of the variable used in the program by using predefined
function type() which returns the data type of the variable.
- Consider the following example to define the values of different data types and checking its
type.

a=10
b=12.45
c="VJTech"
print("Value of a=",a," and data type is",type(a));
print("Value of b=",b," and data type is",type(b));
print("Value of c=",c," and data type is",type(c));

When you run the above program, the output will be:

Value of a=10 and data type is <type, 'int'>


Value of b=12.45 and data type is <type, 'float'>
Value of c=VJTech and data type is <type, 'str'>

Following are the data types present in Python:

1. Numeric Types (int, float, complex)


2. String Type (str)
3. Sequence Types (list, tuple, range)
4. Mapping Type (dict)
5. Set Types (set, frozenset)
6. Boolean Type (bool)
7. Binary Types (bytes, bytearray, memoryview).

Python Programming by Mr. Vishal Jadhav Sir’s (VJTech Academy, contact us: +91-9730087674) 10
UNIT-I Introduction and Syntax of Python Program

 Numeric Data Types:


- Integers, floating point numbers and complex numbers present under the Numeric Data
Type category.
- They are defined as int, float and complex class in Python.

Integer (int):

- Integer is a combination of 0 to 9 digits numbers without decimal point.


- Integer number may be positive or negative.
- Integers can be of any length, it is only limited by the memory available.
- Example:

a=10
print("Value of a=",a," and data type is",type(a));

Floating Point Number (float):

- Floating point number is a combination of 0 to 9 digits number with decimal point.


- Floating point number may be positive or negative.
- A floating point number is accurate up to 15 decimal places.
- Float can also be scientific numbers with an "e" to indicate the power of 10.
- Example:

a=10.45
b=12e4
print("Value of a=",a," and data type is",type(a));
print("Value of b=",b," and data type is",type(b));

Complex Number (complex):

- Complex number is a combination of real and imaginary parts.


- In python, complex numbers are written with a "j" as the imaginary part.
- Complex numbers are written in the form, x + yj, where x is the real part and y is the
imaginary part.
- Example:

b=4+3.4j
print("Value of b=",b," and data type is",type(b));

Python Programming by Mr. Vishal Jadhav Sir’s (VJTech Academy, contact us: +91-9730087674) 11
UNIT-I Introduction and Syntax of Python Program

 Python Strings:
- The collections of characters is known as String. Characters may be alphabets, numbers or
special symbols.
- String should be represented by using single quotes or double quotes.
- For String data type,predefined class str is used.
- Positive and Negative index associated with the String value.
- String positive index should begin with 0 and end with SIZE-1.
- Negative index should begin with -1 from the last element.
- Multi-line strings can be denoted using triple quotes, ''' or """.
- When we use plus (+) sign with String then it work as concatenation operator and when we
use asterisk(*) sign with String then it work as repetition operator.
- Strings are immutable. It means once it is created, you can not change it later.
- Subscript [] and index number is used to access any particular element from the string.
- We can use slice [:] operators to access the data of the strings.
- Example:
str1="VJTech Academy";
print(str1);
print(str1[:]);
print(str1[7:]);
print(str1[2:6]);
print(str1+" Awasari");
print(str1*2);

When you run the above program, the output will be:

VJTech Academy
VJTech Academy
Academy
Tech
VJTech Academy Awasari
VJTech AcademyVJTech Academy

 Python List:
- List is an ordered sequence of items.
- It is one of the most used datatype in Python and is very flexible.
- All the items in a list do not need to be of the same type.
- List is a collection of mixed data types of items.
- List should be represented by using square bracket [ ].
- For List data type,predefined class list is used.
- Positive and Negative index associated with the list items.
- List positive index should begin with 0 and end with SIZE-1.
- Negative index should begin with -1 from the last element.
- Lists are mutable. It means once it is created, you can change it later.

Python Programming by Mr. Vishal Jadhav Sir’s (VJTech Academy, contact us: +91-9730087674) 12
UNIT-I Introduction and Syntax of Python Program

- Subscript [] and index number is used to access any particular element from the list.
- We can use slice [:] operator to access the items of the list.
- Example:
a = [5,10,15,20,25,30,35,40]
print(a)
print(a[2])
print(a[0:3])
print(a[5:])

When you run the above program, the output will be:

[5, 10, 15, 20, 25, 30, 35, 40]


15
[5, 10, 15]
[30, 35, 40]

 Python Tuple:
- Tuple is an ordered sequence of items.
- All the items in a Tuple do not need to be of the same type.
- Tuple is a collection of mixed data types of items.
- Tuple should be represented by using parentheses ().
- For Tuple data type,predefined class tuple is used.
- Positive and Negative index associated with the Tuple items.
- Tuple positive index should begin with 0 and end with SIZE-1.
- Tuple index should begin with -1 from the last element.
- Tuple are immutable. It means once it is created, you can not change it later.
- Subscript [] and index number is used to access any particular element from the Tuple.
- We can use slice [:] operator to access the items of the Tuple
- Tuples are used to read only data and it is faster than list as it cannot change dynamically..
- Example:
a = (5,10,15,20,25,30,35,40)
print(a)
print(a[2])
print(a[0:3])
print(a[5:])

When you run the above program, the output will be:

(5, 10, 15, 20, 25, 30, 35, 40)


15
(5, 10, 15)
(30, 35, 40)

Python Programming by Mr. Vishal Jadhav Sir’s (VJTech Academy, contact us: +91-9730087674) 13
UNIT-I Introduction and Syntax of Python Program

 Python Set:
-Set is an unordered collection of unique items.
-Set is defined by values separated by comma inside braces { }.
-Items in a set are not ordered.
-We can perform set operations like union, intersection on two sets.
-Set have unique values. They eliminate duplicates.
- Set are unordered collection of items and index numbers are not associated with it. Hence the
slicing operator [:] does not work.
- Example:

a = {5,10,15,20,25,30,35,40}
print(a)

When you run the above program, the output will be:

{35, 5, 40, 10, 15, 20, 25, 30}

 Python Dictionary:
- Dictionary is an ordered collection of items and it should be represented by using (key:value)
pairs format.
- It is generally used when we have a huge amount of data.
- Dictionaries are optimized for retrieving data. We must know the key to retrieve the value.
- In Python, dictionaries are defined by using curly bracket {} with each item being a pair in the
form key:value.
- Key and value can be of any data type.
- Example:

d = {1:'Pune', 2:'Solapur', 3:'Tuljapur', 4:'Thane'};


print("First city is ",d[1]);
print("Fourth city is ",d[4]);
print (d);
print (d.keys());
print (d.values());

When you run the above program, the output will be:

First city is Pune


Fourth city is Thane
{1: 'Pune', 2: 'Solapur', 3: 'Tuljapur', 4: 'Thane'}
dict_keys([1, 2, 3, 4])
dict_values(['Pune', 'Solapur', 'Tuljapur', 'Thane'])

Python Programming by Mr. Vishal Jadhav Sir’s (VJTech Academy, contact us: +91-9730087674) 14
UNIT-I Introduction and Syntax of Python Program

 Python Type Conversion (Type Casting):


- The process of converting the value of one data type to another data type is called as Type
conversion.
- It is also known as Type casting.
- Python promotes conversion of lower datatype (integer) to higher data type (float) to avoid
data loss.
- There are two types of type conversion.
1. Implicit Type Conversion
2. Explicit Type Conversion

Implicit Type Conversion:

- The type casting which is done by system is known as Implicit type conversion.
- Python automatically convert one type value to another type.
- It does not require any user involvement.
- Example:
a = 123
b = 1.23
c = a + b

print("datatype of a:",type(a))
print("datatype of b:",type(b))

print("Value of c:",c)
print("datatype of c:",type(c))

When you run the above program, the output will be:

datatype of a: <class 'int'>


datatype of b: <class 'float'>
Value of c: 124.23
datatype of c: <class 'float'>

Explicit Type Conversion:

- The type casting which is done by programmer is known as Explicit type conversion.
- Here Programmer will convert the data type of an object to required data type.
- We use the predefined functions like int(), float(), str(), etc to perform explicit type
conversion..
- Syntax:
Variable_Name = (required_datatype) (Expression);

- Example:
a = 123
b = 1.23

Python Programming by Mr. Vishal Jadhav Sir’s (VJTech Academy, contact us: +91-9730087674) 15
UNIT-I Introduction and Syntax of Python Program

c = (float)(a + b)

print("datatype of a:",type(a))
print("datatype of b:",type(b))

print("Value of c:",c)
print("datatype of c:",type(c))

When you run the above program, the output will be:

datatype of a: <class 'int'>


datatype of b: <class 'float'>
Value of c: 124.23
datatype of c: <class 'float'>

 Python Input and Output Operations:


- There are two built-in functions print() and input() are used to perform I/O operations in
Python.

Python Output Using print() function:

- print() function is used to print output messages on output screen.


- This is predefined function of Python language.
- Syntax:
print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)

Where:
objects -> Value to be printed.
sep -> The separator is used between the values. It’s default value is a space character.
end -> After all values are printed then end is printed. It’s default value is a new line.
file -> The file is the object where the values are printed and its default value is
sys.stdout (screen)
- Example:
print(1,2,3,4)
print(1,2,3,4,sep='*')
print(1,2,3,4,sep='#',end='&')

When you run the above program, the output will be:

1 2 3 4
1*2*3*4
1#2#3#4&

Python Programming by Mr. Vishal Jadhav Sir’s (VJTech Academy, contact us: +91-9730087674) 16
UNIT-I Introduction and Syntax of Python Program

Python Input Using input() function:

- input() function is used to take input from user through keyboard.


- This is predefined function of Python language.
- Whatever the value returned by using input() function, by default it is string type value. To
convert this into a number, we can use int() or float() functions.
- Syntax:
input([message])

Where:
message -> This is the string which we wish to display on the screen. It is optional.

- Example:
no=input("Enter any Value: ")
print("You have entered value of no= ",no);

When you run the above program, the output will be:

Enter any Value: 123


You have entered value of no= 123

Python Programming by Mr. Vishal Jadhav Sir’s (VJTech Academy, contact us: +91-9730087674) 17
UNIT-II Python Operators and Control Flow Statements

 Python Operators:

- Operators are used to perform operations on variables and values.


- Operators are the special symbols which indicate operation to be perform.
- Following are the types of operators present in Python.
1. Arithmetic Operators
2. Comparison Operators
3. Logical Operators
4. Bitwise Operators
5. Assignment Operators
6. Membership Operators
7. Identity Operators

1. Arithmetic Operators:

- Arithmetic operators are used to perform mathematical operations like addition, subtraction,
multiplication etc.
- Following are the list of Arithmetic operators present in Python

Operator Meaning
+ Addition
- Substraction
* Multiplication
/ Division
// Floor Division
% Modulus – remainder calculator
** Exponent

- Example:
x = 15
y = 4

print("x + y =",x+y)

print("x - y =",x-y)

print("x * y =",x*y)

print("x / y =",x/y)

print("x // y =",x//y)

print("x ** y =",x**y)

Python Programming by Mr. Vishal Jadhav Sir’s (VJTech Academy, contact us: +91-9730087674) 1
UNIT-II Python Operators and Control Flow Statements

When you run the above program, the output will be:

x + y = 19
x - y = 11
x * y = 60
x / y = 3.75
x // y = 3
x ** y = 50625

2. Comparision Operators:

- Comparison operators are used to compare values.


- It give result either True or False according to the condition.
- Following are the list of comparision operators present in Python

Operator Meaning
< Less Than
> Greater Than
<= Less Than or Equal To
>= Greater Than or Equal To
== Equal To
!= Not Equal To

- Example:
x = 10
y = 12

print("x > y is", x>y)

print("x < y is", x<y)

print("x == y is", x==y)

print("x != y is", x!=y)

print("x >= y is", x>=y)

print("x <= y is", x<=y)

When you run the above program, the output will be:

x > y is False
x < y is True
x == y is False

Python Programming by Mr. Vishal Jadhav Sir’s (VJTech Academy, contact us: +91-9730087674) 2
UNIT-II Python Operators and Control Flow Statements

x != y is True
x >= y is False
x <= y is True

3. Logical Operators:

- Logical operators are the and, or, not operators.


- It give result either True or False according to the condition.
- Following are the list of Logical operators present in Python

Operator Meaning
and It returns True if its both sides are True otherwise False
or It returns False if its both sides are False otherwise True
not Reverse the Result, returns False if the result is True.

- Example:
print("10>5 and 10==10 Result is ",10>5 and 10==10)

print("150<50 or 15!=15 Result is",150<50 or 15!=15)

print("not(12>5) Result is",not(12>5))

When you run the above program, the output will be:

10>5 and 10==10 Result is True


150<50 or 15!=15 Result is False
not(12>5) Result is False

4. Bitwise Operators:

- Bitwise operators are used to work with binary numbers


- Bitwise operator works on bits and performs bit by bit operation.
- Following are the list of Bitwise operators present in Python

Operator Meaning Description


& Bitwise AND If both bits are 1 then output is 1 otherwise 0.
| Bitwise OR If both bits are 0 then output is 0 otherwise 1.
^ Bitwise XOR If both bits are different then output is 1 otherwise 0
~ Bitwise NOT Inverts all the bits
<< Bitwise left Shift Shift left by pushing zeros in from the right side and let
the leftmost bits fall off
>> Bitwise right shift Shift right by pushing zeros in from the left side and let
the rightmost bits fall off

Python Programming by Mr. Vishal Jadhav Sir’s (VJTech Academy, contact us: +91-9730087674) 3
UNIT-II Python Operators and Control Flow Statements

- Example:
x=10
y=4
print("x&y Result is", x&y);
print("x|y Result is", x|y);
print("x^y Result is", x^y);
print("~x Result is", ~x);
print("x<<2 Result is", x<<2);
print("x>>2 Result is", x>>2);

When you run the above program, the output will be:

x&y Result is 0
x|y Result is 14
x^y Result is 14
~x Result is -11
x<<2 Result is 40
x>>2 Result is 2

5. Assignment Operators:

- Assignment operator is used to assign right side expression result or value to the left side
variable.
- Assignment operators are used in Python to assign values to variables.
- Following are the Assignment operators in Python:

Operator Example Same as


= X=5 X=5
+= X+=5 X=X+5
-= X-=5 X=X-5
*= X*=5 X=X*5
/= X/=5 X=X/5
//= X//=5 X=X//5
**= X**=5 X=X**5
&= X&=5 X=X&5
|= X|=5 X=X|5
^= X^=5 X=X^5
<<= X<<=5 X=X<<5
>>= X>>=5 X=X>>5

Python Programming by Mr. Vishal Jadhav Sir’s (VJTech Academy, contact us: +91-9730087674) 4
UNIT-II Python Operators and Control Flow Statements

6. Membership operators:

- in and not in are the membership operators in Python.


- They are used to test whether a value or variable is found in a sequence (string, list, tuple, set
and dictionary).
- In a dictionary we can only test for presence of key, not the value.
- Following are the Membership operators in Python:

Operator Meaning
in True if value/variable is found in the sequence
not in True if value/variable is not found in the sequence

- Example:
x=[10,20,30,40,50]

print("10 in x =>", 10 in x);


print("10 not in x =>", 10 not in x);
print("120 in x =>", 120 in x);
print("120 not in x =>", 120 not in x);

When you run the above program, the output will be:

10 in x => True
10 not in x => False
120 in x => False
120 not in x => True

7. Identity operators:

- is and is not are the identity operators in Python.


- Identity operators are used to compare the objects/variables.
- They are used to check if two values (or variables) are located on the same part of the
memory.
- Following are the identity operators in Python:

Operator Meaning
is True if operands are indentical
is not True if operands are not identical

- Example:
x=10;
y=10;

Python Programming by Mr. Vishal Jadhav Sir’s (VJTech Academy, contact us: +91-9730087674) 5
UNIT-II Python Operators and Control Flow Statements

z=20;

print("x is y =>", x is y);


print("x is not y =>", x is not y);
print("x is not z =>", x is not z);
print("x is z =>", x is z);

When you run the above program, the output will be:

x is y => True
x is not y => False
x is not z => True
x is z => False

Python Programming by Mr. Vishal Jadhav Sir’s (VJTech Academy, contact us: +91-9730087674) 6
UNIT-II Python Operators and Control Flow Statements

 if Statement:
- if statement is one of the types of Decision making statement.
- Decision making statement is required when we want to execute a code only if a certain
condition is satisfied.
- if is a predefined keyword which should be written in small letters.
- Syntx:
if condition:
statement-1
statement-2
---
---
statement-n

- Program controller first test the condition, if condition is True then program controller executes
the body of if statement.
- If condition is False then program controller will not executes the body of if statements.
- In Python programming language, any non-zero and non-null values are assumed as TRUE, and if
it is either zero or null, then it is assumed as FALSE value.
- if statement flowchart:

- Example:
a=int(input("Enter first Number:"))
b=int(input("Enter second Number:"))
if a==b:
print("Both Numbers are Equals");

When you run the above program, the output will be:

Enter first Number:15


Enter second Number:15
Both Numbers are Equals

- In the above example, a==b is the condition. The body of if is executed only if condition a==b is
True otherwise it will not executes the body of if statement.

Python Programming by Mr. Vishal Jadhav Sir’s (VJTech Academy, contact us: +91-9730087674) 7
UNIT-II Python Operators and Control Flow Statements

 if-else Statement:
- if-else statement is one of the types of Decision making statement.
- if and else both are predefined keywords which should be written in small letters.
- Syntx:
if condition:
statement-1
---
---
else:
statement-1
---
---

- Program controller first test the condition, if condition is True then program controller executes
the body of if statement.
- If condition is False then program controller executes the body of else statements.
- In Python programming language, any non-zero and non-null values are assumed as TRUE, and if
it is either zero or null, then it is assumed as FALSE value.
- if-else statement flowchart:

- Example:
a=int(input("Enter first Number:"))
b=int(input("Enter second Number:"))
if a==b:
print("Both Numbers are Equals");
else:
print("Both Numbers are not Equals");

When you run the above program, the output will be:

Enter first Number:15


Enter second Number:15
Both Numbers are Equals

Python Programming by Mr. Vishal Jadhav Sir’s (VJTech Academy, contact us: +91-9730087674) 8
UNIT-II Python Operators and Control Flow Statements

- In the above example, a==b is the condition. The body of if is executed only if condition a==b is
True otherwise it will executes the body of else statement.

 if-elif-else Statement:
- if-elif-else statement is one of the types of Decision making statement.
- if, elif and else all are predefined keywords which should be written in small letters.
- Syntx:
if condition-1:
statements
---
---
elif condition-2:
statements
---
---
elif condition-3:
statements
---
---
else:
statements
---

- Program controller first test the condition-1, if condition-1 is True then program controller
executes the body of if statement.
- If condition-1 is false then program controller test the condition-2, if condition-2 is True then it
will executes the body of if statement.
- If all conditions are False then program controller executes else block statements.
- if-elif-else statement flowchart:

Python Programming by Mr. Vishal Jadhav Sir’s (VJTech Academy, contact us: +91-9730087674) 9
UNIT-II Python Operators and Control Flow Statements

- Example:
marks=int(input("Enter your Marks:"))
if marks>=75:
print("You got Distinction");
elif marks>=60:
print("You got First Class");
elif marks>=40:
print("You are Pass only");
else:
print("You are Fail");

When you run the above program, the output will be:

Enter your Marks:89


You got Distinction

- In the above example, When variable marks value is 89, then ‘You got Distinction’ is
printed. When variable marks value is 66, then ‘You got First Class’ is printed. When
variable marks value is 45, then ‘You are Pass only’ is printed. When variable marks value is
35, then ‘You are Fail’ is printed.

Python Programming by Mr. Vishal Jadhav Sir’s (VJTech Academy, contact us: +91-9730087674) 10
UNIT-II Python Operators and Control Flow Statements

 For Loop Statement:


- for loop statement is one of the types of looping statement in Python.
- for is a predefined keyword which should be written in small letters.
- If we want to run the block of code N no of times then we can use the looping statements.
- The for loop in Python is used to iterate over a sequence (list, tuple, string) or other iterable
objects. Iterating over a sequence is called traversal.
- Syntx:
for val in sequence:
Body of for loop
-------
-------
-------

- In above syntax, val is the variable that takes the value of the item inside the sequence on each
iteration.
- Program controller executes the for loop until it reach the last item in the sequence.
- for loop statement flowchart:

- Example:
# Program to find the sum of all numbers in a list

numbers = [6, 5, 3, 8, 4, 2, 5, 4, 11]

sum = 0
for val in numbers:
sum = sum+val

Python Programming by Mr. Vishal Jadhav Sir’s (VJTech Academy, contact us: +91-9730087674) 11
UNIT-II Python Operators and Control Flow Statements

print("The sum is", sum)

When you run the above program, the output will be:

The sum is 48

- In the above example, When variable marks value is 89, then ‘You got Distinction’ is
printed. When variable marks value is 66, then ‘You got First Class’ is printed. When
variable marks value is 45, then ‘You are Pass only’ is printed. When variable marks value is
35, then ‘You are Fail’ is printed.

The range() function:


- We can generate a sequence of numbers using range() function. For example, range(10) will
generate numbers from 0 to 9.
- We can also define the start, stop and step size as range(start,stop,Increment size). Increment
size defaults to 1 if not provided.
- This function does not store all the values in computer memory. So it remembers the start, stop,
step size and generates the next number.
- We can use the range() function in for loop to iterate through a sequence of numbers.
- Example:
# Program to display ‘VJTech Academy’message on output screen 5 times

for i in range(1,6):
print("VJTech Academy")

When you run the above program, the output will be:

VJTech Academy
VJTech Academy
VJTech Academy
VJTech Academy
VJTech Academy

Python Programming by Mr. Vishal Jadhav Sir’s (VJTech Academy, contact us: +91-9730087674) 12
UNIT-II Python Operators and Control Flow Statements

for loop with else keyword:


- A for loop can have an optional else block as well.
- The else part is executed if all items in the sequence are finished.
- When we use break statement to stop a for loop then program controller ignore the else part
execution.
- In for loop, else part runs if break statement is not executed inside the body.
- Example:
# Program to display ‘VJTech Academy’message on output screen 5 times

for i in range(1,6):
print("VJTech Academy")
else:
print("End of the program")

When you run the above program, the output will be:

VJTech Academy
VJTech Academy
VJTech Academy
VJTech Academy
VJTech Academy
End of the program

- In above example, the for loop prints message on output screen until the loop ends. When the
for loop ends, it executes the block of code in the else statement.

Python Programming by Mr. Vishal Jadhav Sir’s (VJTech Academy, contact us: +91-9730087674) 13
UNIT-II Python Operators and Control Flow Statements

 While Loop Statement:


- while loop statement is one of the types of looping statement in Python.
- while is a predefined keyword which should be written in small letters.
- If we want to run the block of code N no of times then we can use the looping statements.
- In while loop statement, program controller first test the condition if condition if True then it
will execute the body of while loop.
- Again, it will goes to test the condition if condition is again True then it will execute the body of
while loop.
- This process continue until while loop condition become False.
- Syntx:
while condition:
Body of while loop
-------
-------
-------

- In above syntax, program controller executes the while loop body until condition is True.
- While loop statement flowchart:

- Example:
# Program to display ‘VJTech Academy’message on output screen 5 times
i=1
while i<=5:
print("VJTech Academy")
i=1+1

When you run the above program, the output will be:

Python Programming by Mr. Vishal Jadhav Sir’s (VJTech Academy, contact us: +91-9730087674) 14
UNIT-II Python Operators and Control Flow Statements

VJTech Academy
VJTech Academy
VJTech Academy
VJTech Academy
VJTech Academy

- In the above example, program controller print ‘VJTech Academy’ message on output screen 5
times. It will stop the execution of while loop when i value become 6.

while loop with else keyword:


- A while loop can have an optional else block as well.
- The else part is executed when while loop condition is False.
- When we use break statement to stop a while loop then program controller ignore the else part
execution.
- In while loop, else part runs if break statement is not executed inside the body.
- Example:
# Program to display ‘VJTech Academy’message on output screen 5 times
i=1
while i<=5:
print("VJTech Academy")
else:
print("End of the program")

When you run the above program, the output will be:

VJTech Academy
VJTech Academy
VJTech Academy
VJTech Academy
VJTech Academy
End of the program

- In above example, the while loop print message on output screen until the loop ends. When the
while loop condition is false then it executes the block of code in the else statement.

Python Programming by Mr. Vishal Jadhav Sir’s (VJTech Academy, contact us: +91-9730087674) 15
UNIT-II Python Operators and Control Flow Statements

 Break keyword:
- break is a predefined keyword in Python which should be written in small letters.
- We can use break keyword inside the body of looping statements.
- Normally, program controller executes the body of loop unil condition becomes false. But
sometimes their could be situation where we want to terminate the execution of the loop then
we can use the break keyword inside the body of loop.
- When break statement is executed inside the body of loop then program controller terminates
the execution of loop immediately and it will comes out of loop.
- Syntax:
break
- Flowchart of break:

- Example:
# Program to show the use of break keyword
for i in range(1,6):
if i==3:
break
print("Value of i=",i)

When you run the above program, the output will be:

Value of i= 1
Value of i= 2

- In above program, we can see for loop will iterate through the range(1,6). We check that value
of i is 3 if it is 3 then break will executed. Hence, we see in our output that value of i is printed
up to 2. After that, the loop is terminated.

Python Programming by Mr. Vishal Jadhav Sir’s (VJTech Academy, contact us: +91-9730087674) 16
UNIT-II Python Operators and Control Flow Statements

 Continue keyword:
- continue is a predefined keyword in Python which should be written in small letters.
- We can use continue keyword inside the body of looping statements.
- When continue statement is executed inside the body of loop then program controller goes for
the next iteration and skip the execution of rest of the statements.
- Loop does not terminate but continues on with the next iteration.
- Syntax:
continue
- Flowchart of continue:

- Example:
# Program to show the use of continue keyword
for i in range(1,6):
if i==3:
continue
print("Value of i=",i)

When you run the above program, the output will be:

Value of i= 1
Value of i= 2
Value of i= 4
Value of i= 5

- In above program, we can see for loop will iterate through the range(1,6). We check that value
of i is 3 if it is 3 then continue is executed. W can see value of i=3 is not printed in output.

Python Programming by Mr. Vishal Jadhav Sir’s (VJTech Academy, contact us: +91-9730087674) 17
UNIT-II Python Operators and Control Flow Statements

 Pass keyword:
- pass is a predefined keyword in Python which should be written in small letters.
- In Python programming, pass is a null statement.
- The difference between a comment and pass statement in Python is that, while the interpreter
ignores a comment entirely, pass is not ignored.
- However, nothing happens when pass is executed. It results into no operation (NOP).
- Syntax:
pass
- Suppose we have a loop or a function that is not implemented yet, but we want to implement it
in the future.
- They cannot have an empty body. The interpreter would complain. So, we use
the pass statement to construct a body that does nothing.
- Example:
# Program to show the use of pass keyword
numbers=[10,20,30,40,50]
for val in numbers:
pass

When you run the above program, the output will be blank:

Python Programming by Mr. Vishal Jadhav Sir’s (VJTech Academy, contact us: +91-9730087674) 18
UNIT-III Data Structures in Python

 Python List:
- List is an ordered sequence of items.
- All the items in a list do not need to be of the same type.
- List is a collection of mixed data types of items.
- List should be represented by using square bracket [ ].
- For List data type,predefined class list is used.
- Positive and Negative index associated with the list items.
- List positive index should begin with 0 and negative index should begin with -1 from the last
element.
- Lists are mutable. It means once it is created, you can change it later.
- Subscript [] and index number is used to access any individual element from the list.
- We can use slice [:] operator to access the range of items from the list.
- Example:
a = [5,10,15,20,25,30,35,40]
print(a)
print(a[2])
print(a[-3])
print(a[0:3])
print(a[5:])

When you run the above program, the output will be:

[5, 10, 15, 20, 25, 30, 35, 40]


15
30
[5, 10, 15]
[30, 35, 40]

Methods of List:

1) len() :- This method is used to find out the how many items present in list.

- Example:
a = [10,20,30,40,50]
print("Length of list=",len(a))

- Output:
Length of list= 5

2) append() :- To add an item to the end of the list, we use the append() method

- Example:
a = [10,20,30,40,50]
a.append(60)
print("All Items of list=", a)

Python Programming by Mr. Vishal Jadhav Sir’s (VJTech Academy, contact us: +91-9730087674) 1
UNIT-III Data Structures in Python

- Output:
All Items of list= [10, 20, 30, 40, 50, 60]

3) extend() :- To add no of items to the end of the list, we use the extend() method.

- Example:
a = [10,20,30,40,50]
a.extend([60,70,80]);
print("All Items of list=", a)

- Output:
All Items of list= [10, 20, 30, 40, 50, 60, 70, 80]

4) insert() :- To add an item at the specified index, we use the insert() method

- Example:
a = [10,20,30,40,50]
a.insert(1,15)
print("All Items of list=", a)

- Output:
All Items of list= [10, 15, 20, 30, 40, 50, 60]

5) del :- The del keyword is used to delete the specified index value or it can also delete the complete list

- Example:
a = [10,20,30,40,50]
del a[1]
print("list after deleting index 1 value=", a)
#if you want to delete complete list
del a

- Output:
list after deleting index 1 value= [10, 30, 40, 50]

6) remove() :- This method is used to remove the specified item from the list.

- Example:
a = [10,20,30,40,50]
a.remove(40)
print("list after removing 40 value=", a)

- Output:
list after removing 40 value = [10, 20, 30, 50]

Python Programming by Mr. Vishal Jadhav Sir’s (VJTech Academy, contact us: +91-9730087674) 2
UNIT-III Data Structures in Python

6) pop() :- This method is used to remove the specified index value from the list or it will remove the last
value if index is not specified.

- Example:
a = [10,20,30,40,50]
a.pop(1)
print("list after removing index 1 value=", a)
a.pop()
print("list after removing last value=", a)

- Output:
list after removing index 1 value= [10, 30, 40, 50]
list after removing last value= [10, 30, 40]

7) clear() :- This method is used to make an empty list.

- Example:
a = [10,20,30,40,50]
a.clear()
print("List of Values=",a)

- Output:
List of items= []

8) index() :- This method finds the given element in a list and returns its index number. If the same
element is present more than once, the method returns the index of the first occurrence of the element.

- Example:
a = [10,20,30,40,50]
print("Index of 30 element=", a.index(30))

- Output:
Index of 30 element= 2

9) count() :- This method counts how many times an element present in a list and returns it.

- Example:
a = [10,20,30,40,50,30,30]
print("Count of 30 =", a.index(30))

- Output:
Count of 30 = 3

Python Programming by Mr. Vishal Jadhav Sir’s (VJTech Academy, contact us: +91-9730087674) 3
UNIT-III Data Structures in Python

10) sort() :- This method sorts the elements of a given list in a specific order - Ascending or Descending.

- Example:
a = [10,20,30,40,50,30,30]
a.sort();
print("Sort the element in Ascending order =", a)
b = [10,20,30,40,50,30,30]
b.sort(reverse=True)
print("Sort the element in Descending order =", b)

- Output:
Sort the element in Ascending order = [10, 20, 30, 30, 30, 40, 50]
Sort the element in Descending order = [50, 40, 30, 30, 30, 20, 10]

11) reverse() :- This method is used to reverses the elements of given list.

- Example:
a = [10,20,30,40,50]
a.reverse();
print("Reverse the list elements =", a)

- Output:
Reverse the list elements = [50, 40, 30, 20, 10]

12) copy() :- This method is used copy all elements of one list to another list.

- Example:
a = [10,20,30,40,50]
b=a.copy();
print("Copied list b elements =", b)

- Output:
Copied list b elements = [10, 20, 30, 40, 50]

13) min() :- This method is used to find out the minimum element in the list.

- Example:
a = (10,20,30,40,50,30,30)
print("Minimum element =", min(a))

- Output:
Minimum element = 10

14) max() :- This method is used to find out the maximum element in the list.

- Example:
a = (10,20,30,40,50,30,30)

Python Programming by Mr. Vishal Jadhav Sir’s (VJTech Academy, contact us: +91-9730087674) 4
UNIT-III Data Structures in Python

print("Maximum element =", max(a))

- Output:
Maximum element = 50

Python Programming by Mr. Vishal Jadhav Sir’s (VJTech Academy, contact us: +91-9730087674) 5
UNIT-III Data Structures in Python

 Python Tuple:
- Tuple is an ordered sequence of items.
- All the items in a Tuple do not need to be of the same type.
- Tuple is a collection of mixed data types of items.
- Tuple should be represented by using parentheses ().
- For Tuple data type,predefined class tuple is used.
- Positive and Negative index associated with the Tuple items.
- Positive index should begin with 0 and negative index should begin with -1 from the last element.
- Tuple are immutable. It means once it is created, you can not change it later.
- Subscript [] and index number is used to access any particular element from the Tuple.
- We can use slice [:] operator to access the range of items from the Tuple
- Tuples are used to read only data and it is faster than list as it cannot change dynamically.
- Example:
a = (5,10,15,20,25,30,35,40)
print(a)
print(a[2])
print(a[-3])
print(a[0:3])
print(a[5:])

When you run the above program, the output will be:

(5, 10, 15, 20, 25, 30, 35, 40)


15
30
(5, 10, 15)
(30, 35, 40)

Methods of Tuples:

1) len() :- This method is used to find out the how many items present in tuple.

- Example:
a = (10,20,30,40,50)
print("Length of Tuple=",len(a))

- Output:
Length of Tuple= 5

2) del :- The del keyword is used to delete the tuple completely.

- Example:
a = (10,20,30,40,50)
del a
print(a);

Python Programming by Mr. Vishal Jadhav Sir’s (VJTech Academy, contact us: +91-9730087674) 6
UNIT-III Data Structures in Python

- Output:
NameError: name 'a' is not defined

3) index() :- This method finds the given element in a tuple and returns its index number. If the same
element is present more than once, the method returns the index of the first occurrence of the element.

- Example:
a = (10,20,30,40,50)
print("Index of 30 element=", a.index(30))

- Output:
Index of 30 element= 2

4) count() :- This method counts how many times an element present in a tuple and returns it.

- Example:
a = (10,20,30,40,50,30,30)
print("Count of 30 =", a.index(30))

- Output:
Count of 30 = 3

5) min() :- This method is used to find out the minimum element in the Tuple.

- Example:
a = (10,20,30,40,50,30,30)
print("Minimum element =", min(a))

- Output:
Minimum element = 10

6) max() :- This method is used to find out the maximum element in the Tuple.

- Example:
a = (10,20,30,40,50,30,30)
print("Maximum element =", max(a))

- Output:
Maximum element = 50

Python Programming by Mr. Vishal Jadhav Sir’s (VJTech Academy, contact us: +91-9730087674) 7
UNIT-III Data Structures in Python

 Python Set:
- Set is an unordered collection of unique items.
- Set is defined by values separated by comma inside curly bracket { }.
- Items in a set are not ordered.
- We can perform set operations like union, intersection on two sets.
- Set have unique values. They eliminate duplicates.
- Set are unordered collection of items and index numbers are not associated with it. Hence the
slicing operator [:] does not work.
- Example:

a = {5,10,15,20,25,30,35,40}
print(a)

When you run the above program, the output will be:

{35, 5, 40, 10, 15, 20, 25, 30}

Methods of Set:

1) len() :- This method is used to find out the how many items present in list.

- Example:
a = {10,20,30,40,50}
print("Length of set=",len(a))

- Output:
Length of set= 5

2) add() :- To add new item to the set, we use the add() method

- Example:
a = {10,20,30,40,50}
a.add(60)
print("All elements of set=", a)

- Output:
All elements of set= {40, 10, 50, 20, 60, 30}

3) update() :- To add multiple items to the set, we use the update() method.

- Example:
a = {10,20,30,40,50}
a.update([60,70,80]);
print("All elements of set=", a)

Python Programming by Mr. Vishal Jadhav Sir’s (VJTech Academy, contact us: +91-9730087674) 8
UNIT-III Data Structures in Python

- Output:
All elements of set= {70, 40, 10, 80, 50, 20, 60, 30}

4) del :- The del keyword is used to delete the set completely.

- Example:
a = {10,20,30,40,50}
del a
print(a)

- Output:
NameError: name 'a' is not defined

5) remove() :- This method is used to remove the specified item from the set.

- Example:
a = {10,20,30,40,50}
a.remove(40)
print("Set after removing 40 value=", a)

- Output:
Set after removing 40 value= {10, 50, 20, 30}

6) pop() :- This method is used to remove remove the last item. Remember that sets are unordered, so
you will not know what item that gets removed. The return value of the pop() method is the removed
item.

- Example:
a = {10,20,30,40,50}
print("Removed Element=", a.pop())

- Output:
Removed Element= 40

7) clear() :- This method is used to make an empty list.

- Example:
a = {10,20,30,40,50}
a.clear()
print("Set elements=",a)

- Output:
Set elements= set()

8) union() :- This method return a set that contains all items from both sets, duplicates are removed.

Python Programming by Mr. Vishal Jadhav Sir’s (VJTech Academy, contact us: +91-9730087674) 9
UNIT-III Data Structures in Python

- Example:
a = {10,20,30,40,50}
b={20,60,70}
c=a.union(b)
print("Union set=",c)

- Output:
Union set= {50, 20, 70, 40, 10, 60, 30}

9) difference() :- This method return set that contains the items that only exist in set a, and not in set b.

- Example:
a = {10,20,30,40,50}
b={20,60,70}
c=a.difference(b)
print("Difference set=",c)

- Output:
Difference set= {40, 10, 50, 30}

10) intersection() :- This method return a set that contains the items that exist in both set a and b.

- Example:
a = {10,20,30,40,50}
b={20,60,70}
c=a.intersection(b)
print("Intersection set=",c)

- Output:
Intersection set= {20}

Python Programming by Mr. Vishal Jadhav Sir’s (VJTech Academy, contact us: +91-9730087674) 10
UNIT-III Data Structures in Python

 Python Dictionary:
- Dictionary is an ordered collection of items and it should be represented by using (key:value) pairs
format.
- It is generally used when we have a huge amount of data.
- Dictionaries are optimized for retrieving data. We must know the key to retrieve the value.
- In Python, dictionaries are defined by using curly bracket {} with each item being a pair in the form
of key:value.
- Key and value can be of any data type.
- Example:

d = {1:'Pune', 2:'Solapur', 3:'Tuljapur', 4:'Thane'}


print("First city is ",d[1])
print("Fourth city is ",d[4])
print (d)

When you run the above program, the output will be:

First city is Pune


Fourth city is Thane
{1: 'Pune', 2: 'Solapur', 3: 'Tuljapur', 4: 'Thane'}

Methods of Dictionary:

1) len() :- This method is used to find out the how many items (key:value pairs) present in dictionary.

- Example:
a = {1:'Pune', 2:'Solapur', 3:'Tuljapur', 4:'Thane'}
print("Length of Dictionary=",len(a))

- Output:
Length of Dictionary= 3

2) del :- The del keyword is used to delete the specified key name or it can also delete the complete
dictionary

- Example:
a = {1:'Pune', 2:'Solapur', 3:'Tuljapur', 4:'Thane'}
del a[1]
print("list after deleting key 1 =", a)
#if you want to delete complete dictionary
del a

- Output:
list after deleting key 1 = {2: 'Solapur', 3: 'Tuljapur', 4: 'Thane'}

Python Programming by Mr. Vishal Jadhav Sir’s (VJTech Academy, contact us: +91-9730087674) 11
UNIT-III Data Structures in Python

3) pop() & popitem() :- The pop() method is used to remove the specified key value from the dictionary.
The popitem() method is used to remove the last inserted element from the dictionary.

- Example:
a = {1:'Pune', 2:'Solapur', 3:'Tuljapur', 4:'Thane'}
a.pop(1)
print("Dictionary after removing key 1=", a)
a.popitem()
print("Dictionary after removing last element=", a)

- Output:
Dictionary after removing key 1= {2: 'Solapur', 3: 'Tuljapur', 4: 'Thane'}
Dictionary after removing last element= {2: 'Solapur', 3: 'Tuljapur'}

4) clear() :- This method is used to make an empty list.

- Example:
a = {1:'Pune', 2:'Solapur', 3:'Tuljapur', 4:'Thane'}
a.clear()
print("Elements of Dictionary=",a)

- Output:

5) copy() :- This method is used copy all elements of one dictionary to another dictionary.

- Example:
a = {1:'Pune', 2:'Solapur', 3:'Tuljapur', 4:'Thane'}
b=a.copy();
print("Copied dict b elements =", b)

- Output:
Copied dict b elements = {1: 'Pune', 2: 'Solapur', 3: 'Tuljapur', 4: 'Thane'}

6) min() :- This method is used to find out the minimum key element in the dictionary.

- Example:
a = {1:'Pune', 2:'Solapur', 3:'Tuljapur', 4:'Thane'}
print("Minimum key element =", min(a))

- Output:
Minimum key element = 1

7) max() :- This method is used to find out the maximum key element in the dictionary.

- Example:
a = {1:'Pune', 2:'Solapur', 3:'Tuljapur', 4:'Thane'}
print("Maximum key element =", max(a))

Python Programming by Mr. Vishal Jadhav Sir’s (VJTech Academy, contact us: +91-9730087674) 12
UNIT-III Data Structures in Python

- Output:
Maximum key element = 4

8) get() :- This method is used to returns the value for the specified key if key is in dictionary.

- Example:
a = {1:'Pune', 2:'Solapur', 3:'Tuljapur', 4:'Thane'}
print("Value =", a.get(3))

- Output:
Value = Tuljapur

9) update() :- This method is used to updates the dictionary. If key value is already present then its
corresponding value will get changed. If key value not present then it will add new entry in the
dictionary.

- Example:
d = {1: "one", 2: "three"}
d1 = {2: "two"}

# updates the value of key 2


d.update(d1)
print(d)

d1 = {3: "three"}

# adds element with key 3


d.update(d1)
print(d)

- Output:
{1: 'one', 2: 'two'}
{1: 'one', 2: 'two', 3: 'three'}

10) keys() & values() :- The keys() method display list of all keys in the dictionary. The values() method
display list of all values in the dictionary.

- Example:
a = {1:'Pune', 2:'Solapur', 3:'Tuljapur', 4:'Thane'}
print("All Keys=",a.keys())
print("All Values=",a.values())

- Output:
All Keys= dict_keys([1, 2, 3, 4])
All Values= dict_values(['Pune', 'Solapur', 'Tuljapur', 'Thane'])

Python Programming by Mr. Vishal Jadhav Sir’s (VJTech Academy, contact us: +91-9730087674) 13

You might also like