Merged
Merged
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.
Python Programming by Mr. Vishal Jadhav Sir’s (VJTech Academy, contact us: +91-9730087674) 1
UNIT-I Introduction and Syntax of Python Program
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.
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
as elif if or yield
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:
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:
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);
My Roll No:1010
Roll_No = 1010;
print("My Roll No:",Roll_No);
Roll_No = 2020;
print("My Roll No:",Roll_No);
My Roll No:1010
My Roll No:2020
print("Value of a=",a);
print("Value of b=",b);
print("Value of c=",c);
Value of a=56
Value of a=3.2
Value of a=Hello
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
- 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:
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:
Python Programming by Mr. Vishal Jadhav Sir’s (VJTech Academy, contact us: +91-9730087674) 9
UNIT-I Introduction and Syntax of Python Program
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:
Python Programming by Mr. Vishal Jadhav Sir’s (VJTech Academy, contact us: +91-9730087674) 10
UNIT-I Introduction and Syntax of Python Program
Integer (int):
a=10
print("Value of a=",a," and data type is",type(a));
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));
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:
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:
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:
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:
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-I Introduction and Syntax of Python Program
- 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:
- 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:
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
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:
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:
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:
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
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:
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)
When you run the above program, the output will be:
4. Bitwise Operators:
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:
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:
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]
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:
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;
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:
- 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:
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:
- 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
- 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
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
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.
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 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
- 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.
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:
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]
- 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
- 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:
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
- 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:
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}
- 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
- 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:
When you run the above program, the output will be:
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'}
- 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"}
d1 = {3: "three"}
- 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