Leela Soft Python Madhu
Python History
Python laid its foundation in the late 1980s.
The implementation of Python was started in the December 1989 by Guido Van
Rossum.
In February 1991, van Rossum published the code.
Python Introduction:
"Python is a programming language that lets our work more quickly and integrates our
systems more effectively."
Python is a general purpose, dynamic, high level and interpreted programming language. It
supports Object Oriented programming approach to develop applications.
Python is easy to learn yet powerful and versatile scripting language which makes it attractive
for Application Development.
Python's syntax and dynamic typing with its interpreted nature, makes it an ideal language for
scripting and rapid application development.
Python supports multiple programming pattern, including object oriented, imperative and
functional or procedural programming styles.
Python makes the development and debugging fast because there is no compilation step
included in python development and edit-test-debug cycle is very fast.
Why the name Python?
No. It wasn't named after a dangerous snake. Rossum was fan of a comedy series from late
seventies. The name "Python" was adopted from the same series "Monty Python's Flying
Circus". Python was named for the BBC TV show Monty Python's Flying Circus.
Where we can use Python:
Python is known for its general-purpose nature that makes it applicable in almost each domain
of software development.
Desktop Applications.
Web applications (DJango*, TurboGears, web2py, Flask,…)
Database Applications* (SQL)
Networking Applications
Games
www.leelasoft.com Cell: 78 42 66 47 66
Leela Soft Python Madhu
Data Analysis
Machine Learning
AI
IoT
Features of Python (OR) Python Features and Advantages
1. Easy to Code:
Python is a very high-level programming language, yet it is effortless to learn. Anyone can learn to code
in Python in just a few hours or a few days. Mastering Python and all its advanced concepts, packages
and modules might take some more time. However, learning the basic Python syntax is very easy, as
compared to other popular languages like C, C++, and Java.
2. Easy to Read:
Python code looks like simple English words. There is no use of semicolons or brackets, and the
indentations define the code block. We can tell what the code is supposed to do simply by looking at it.
3. Free and Open-Source:
Python is developed under an OSI-approved open source license, making it freely usable and
distributable, even for commercial use. Python's license is administered by the Python Software
Foundation. It can also be freely modified and re-distributed. Python can be downloaded from the
official Python website https://www.python.org/downloads/.
4. High-level Language:
Python is a high-level programming language because programmers don’t need to remember the
system architecture, nor do they have to manage the memory. This makes it super programmer-friendly
and is one of the key features of Python.
5. Expressive:
'Expressive' means that it's easy to write code that's easy to understand, both for the compiler and for a
human reader. Python needs to use only a few lines of code to perform complex tasks.
For example, to display Hello World, we simply need to type one line -
print("Hello World")
For example, to display a message five times we can use for loop as:
for i in range(5):
print("Python is Easy...!")
Other languages like Java or C would take up multiple lines to execute this.
6. Dynamically Typed:
www.leelasoft.com Cell: 78 42 66 47 66
Leela Soft Python Madhu
Many programming languages need to declare the type of the variable before they are using. Python is
a dynamically typed language. Which means, in Python there is no need to declare the type of a
variable. Whenever we assign a value to the variable, based on the value the type will be allocated
automatically. This makes Python a dynamically typed language.
For example, if you have to assign an integer value 20 to a variable “x”, we don’t need to write int x =
20. We just have to write x = 15.
7. Interpreted:
When a programming language is interpreted, it means that the source code is executed line by line,
and not all at once. Programming languages such as C++ or Java are not interpreted, and hence need to
be compiled first to run them. There is no need to compile Python because it is processed at runtime by
the interpreter.
8. Platform Independent:
Python is a Platform-Independent programming language. It means Python can run equally easily on a
variety of platforms like Windows, Linux or Unix, and many more Operating Systems. So, there is no
need to write a separate code for each Operating System, as the same code can run on multiple
platforms. Python uses PVM (Python Virtual Machine) to convert python code to machine
understandable code.
9. Portability:
The python applications or portable. The applications which are developed by python on one platform
are going to execute any platform without making any changes. To achieve the portability feature for
every Operating System a separate python software is developed for every version.
10. Both Object-Oriented and Procedure-Oriented:
A programming language is Object-Oriented if it focuses design around data and objects, rather than
functions and logic. We can implement Object Oriented Programming features like Encapsulation,
Polymorphic, Inheritance and Abstraction in the Python programming language. On the contrary, a
programming language is Procedure-Oriented if it focuses more on functions (code that can be reused).
One of the critical features of Python is that it supports both Object-Oriented and Procedure-Oriented
programming.
11. Python is Embeddable:
We can embed the Python Code into other languages such as C, C++, Java, Etc., To provide the scripting
capabilities to other languages we can use the Python Code in it.
www.leelasoft.com Cell: 78 42 66 47 66
Leela Soft Python Madhu
12. Extensible:
A programming language is said to be extensible if it can be extended to other languages. Python code
can also be written in other languages like C++, making it a highly extensible language.
13. Robust Standard Library:
Python has an extensive standard library available for anyone to use. This means that programmers
don’t have to write their code for every single thing unlike other programming languages. There are
libraries for image manipulation, databases, unit-testing, expressions and a lot of other functionalities.
In addition to the standard library, there is also a growing collection of thousands of components, which
are all available in the Python Package Index.
14. Other Advanced Programming Features:
Python contains several advanced programming features such as generators (used to create iterators
with a different approach that most other languages) and list comprehensions (used to create new lists
from other iterables). Python also has automatic memory management eliminating the need to
manually allocate and free memory in the code.
15. Develop GUI & Web Application:
One of the key aspects of any programming language is support for GUI or Graphical User Interface. A
user can easily interact with the software using a GUI. Python offers various toolkits, such as Tkinter,
wxPython and JPython, which allows for GUI's easy and fast development. We can also develop Web
applications using Python Language.
16. Simplify Complex Software Development:
Python can be used to develop both desktop and web apps and complex scientific and numerical
applications. Python's data analysis features help you create custom big data solutions without so much
time and effort. We can also use the Python Data Visualization libraries and API's to present data in a
more appealing way. Several advanced software developers use Python to accomplish high-end AI and
Natural Language processing tasks.
Writing and Executing First Python Program
Step 1: Open IDLE:
Start Menu -> All Programs -> Python3.7 ->click on IDLE
Step 2: Open a New File in IDLE:
File Menu->New File
Step 3: Then Write Our Script:
print("Welcome to Python Classes")
print("Welcome to Leela Soft Tech.")
www.leelasoft.com Cell: 78 42 66 47 66
Leela Soft Python Madhu
Step 4: Then Save The File:
Save the file with .py extension
Step 5: Then Run That File:
In Menu Bar of a File, Click on Run Menu ->Run Module (F5).
Step 6: Output:
Then the output will be displayed on another window.
Identifiers:
Every name in Python is called as an Identifier. That name may be class name, method name,
function or variable name.
Rules define an Identifiers in Python
Identifiers are the names given to the fundamental building blocks in a program.
These can be variables, class, object, functions, lists, dictionaries etc.
There are certain rules defined for naming i.e., Identifiers.
Allowed characters are a-z, A-Z, 0-9, ( _ ).
Keywords (reserved words) should not be used as an identifier name.
Python is case sensitive.
First character of an identifier can be character, underscore ( _ ) but not digit.
White spaces are not allowed.
Ex:1 Valid Identifiers
stdid, stdname
sub1, sub2
cust_id, cust_name, _empId
Ex:2
1name #not allowed
2id #not allowed
id1 #allowed
n1a #allowed
Ex:3 Keywords
if #not allowed
If #allowed
Ex:4 White Space
emp id #not allowed
emp_id #allowed
Ex:5 Case sensitive
empName
www.leelasoft.com Cell: 78 42 66 47 66
Leela Soft Python Madhu
empname #allowed but both are different
Literals:
It is a constant value assigned to a variable. It may be Integers, Floats, Strings, etc.,
Ex:
emp_id = 101 #integer literal
empName = "Scott" #string literal
empSalary = 2000.00 #float literal
Variables:
A variable is the name given to a memory location. It is the basic unit of storage in a
program.
The value stored in a variable can be changed during program execution.
Variables are used to store the values, by using these values we are achieving the
project requirements.
Example:
For Employee we required:
employeeId, employeeName, employeeSalary,
For Student we required:
studentId, studentName,
In order to use a variable in a Python program we to need to perform one step, i.e, Variable
Initialization.
Syntax:
<identifier> = <value/literal>
Ex:
emp_id = 101
emp_name = "Scott"
emp_salary = 2000.00
Comments in Python:
In Python, we use the hash '#' symbol to start writing a comment.
It extends up to the newline character. "Python Interpreter ignores comment".
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 does not have a hard time figuring it out.
Example:
#This is a comment, Here print() function prints the value
www.leelasoft.com Cell: 78 42 66 47 66
Leela Soft Python Madhu
print("Welcome to Python")
Multi-line comments:
If we have comments that extend multiple lines, one way of doing it is to use hash '#' in the
beginning of each line.
Example:
#This is a long comment
#
#and it extends up to multiple lines
Reserved Words:
Keywords are the reserved words in Python. They are used to define the syntax and
structure of the Python language.
We cannot use a keyword as variable name, function name or any other identifier.
In Python, keywords are case sensitive.
There are 35 reserved words in Python up to 3.7
Keywords in Python programming language
False await else import pass
None break except in raise
True class finally is return
and continue for lambda try
as Def from nonlocal while
assert Del global not with
async Elif if or yield
Input And Output Statements:
print() function:
Print objects to the text stream file or console, separated by 'sep' and followed by 'end'.
Syntax of print() function:
print(value,.., sep=' ', end='\n', file=sys.stdout, flush=False)
>>>print(1,2,3,4)
1 2 3 4
>>>print(1,2,3,4,sep='*')
1*2*3*4
>>>print(1,2,3,4,sep='#',end='&')
1#2#3#4&
www.leelasoft.com Cell: 78 42 66 47 66
Leela Soft Python Madhu
Reading dynamic input from the keyboard:
input():
input() function can be used to read data directly in our required format. We are not required
to perform type casting.
x=input("Enter Value)
type(x)
Example:
a = input("Enter a Number :")
b = input("Enter a Number :")
print("Value of 'a' is :",a)
print("Value of 'b' is :",b)
Python Indentation:
Most of the programming languages like C, C++, Java use braces { } 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 un-
indented line. The amount of indentation is up to us, but it must be consistent throughout that
block.
Generally, four whitespaces are used for indentation and is preferred over tabs.
Example:
for i in range(1, 11):
print(i)
if i == 5:
break
Example:
>>>print(1000)
1000
>>> print(1000) (Here Starting two spaces are there)
IndentationError: unexpected indent
Indentation can be ignored in line continuation. But it is recommended to follow indent. It
makes the code more readable.
www.leelasoft.com Cell: 78 42 66 47 66
Leela Soft Python Madhu
Example:1
if True:
print('Hello')
a = 5
Data types in Python:
int datatype:
Integral values: ...,-2,-1,0,1,2,.....
We can represent int values in 4 ways:
1. Decimal (by default)
2. Binary
3. Octal
4. Hexa Decimal
1. Decimal(base-10) By default
0-9 (allowed digits but not start with 0)
2. Binary (base-2)
1. 0 and 1(allowed digits)
2. starts with 0 followed by 'b' or 'B'
Ex: a=0b1010,
b=0B1010
c=0B10102 #(Invalid)
3. Octal (base-8)
1. 0-7 (allowed digits)
2. starts with 0 followed by 'o' or 'O'
Ex: a=0o1014,
b=0O1014,
c=0o1237
d=0o1238 #(invalid)
4. Hexa Decimal (base 16)
1. 0-9 and a-f or A-F
2. prefixed with 0x or 0X
Ex: a=0x1039Af
b=0X1039Af
c=0X09ag #(invalid)
www.leelasoft.com Cell: 78 42 66 47 66
Leela Soft Python Madhu
Note:
a=10
b=0o10
c=0b10
d=0x10
Output: only in decimal
Note: There is no concept like size, range for int datatype.
float data type:
For floating point type, we can specify in the form of decimal.
Ex:
f=123.456 #valid
f=0123.456 #valid
f=0X123.456 #invalid
f=0o123.456 #invalid
f=0b123.456 #invalid
Python not supported octal/hexa/binary forms for floating point.
We can specify floating points in the Exponential form also.
Ex:
f=1.2e3 # (1.2*10^3)
>>> a=1.2e100
>>> a
1.2e+100
complex data type:
Complex numbers have a real and imaginary part, which are each a floating point number.
Notation:
a+bj #allowed
a+jb #not allowed
here a and b are int or float type.
'a' is real part and 'b' Imaginary part
j^2=-1 or j =sqrt(-1)
To extract these parts from a complex number 'x', use x.real and x.imag.
www.leelasoft.com Cell: 78 42 66 47 66
Leela Soft Python Madhu
Ex: x=10+20j
Ex: x=2.3+4.5j
x.real #(we can get real part)
x.imag #(we can get imaginaries part)
Example:1
>>> a=10+20j
>>> a
(10+20j)
>>> a.real
10.0
>>> a.imag
20.0
Example:2
>>> a=10.3+20.5j
>>> a
(10.3+20.5j)
>>> a.real
10.3
>>> a.imag
20.5
bool data type:
True, False
str data type:
Textual data in Python is handled with str objects, or strings. Strings are immutable sequences
of Unicode code points.
We can represent the value in the form of:
single quote
double quote
triple quotes
Examples:
Single quotes:
s = 'Welcome to Python'
s = 'Welcome to "Python" Classes'
www.leelasoft.com Cell: 78 42 66 47 66
Leela Soft Python Madhu
Double quotes:
s = "Welcome to Python"
s = "Welcome to 'Python' Classes"
Triple quoted:
s = """Welcome to Python"""
or
s = '''Welcome to Python'''
Ex:
s='Hi Hello'
In python +ve index and -ve index is applicable.
+ve index: 0,1,2,...(left to right)
-ve index: -1,-2,...(right to left)
We can Access string elements based on index:
s[1]= 'i'
If we give out of index:
Ex: a='Hello'
a[6]
here, we get IndexError: string index out of range
Ex:1
a='Hi Hello'
print(a)
Ex:2
a="Hi Hello"
print(a)
Ex:3 (This is for multiple lines representation)
Using single quotation (''')
a= '''
Hi Hello
How are
you '''
print(a)
Using double quotation (""")
a="""Hi Hello
www.leelasoft.com Cell: 78 42 66 47 66
Leela Soft Python Madhu
How are
you"""
print(a)
list data type:
If we want to represent a group of values as a single entity where insertion order required to
preserve and duplicates are allowed, then we should go for list data type.
Example:
list = [10, 10.5, 'Madhu', True, 10]
print(list) #[10, 10.5, 'Madhu', True, 10]
Example:
list=[10,20,30,40]
>>> list[0]
10
>>> list[-1]
40
>>> list[1:3]
[20, 30]
>>> list[0]=100
>>> for i in list : print(i)
tuple data type:
tuple data type is exactly same as list data type except that it is immutable. i.e., we
cannot change values.
Tuple elements can be represented within parenthesis.
Example:
>>>t = (10,20,30,40)
>>>type(t)
<class 'tuple'>
Note: tuple is the read only version of list.
range Data Type:
range Data Type represents a sequence of numbers.
www.leelasoft.com Cell: 78 42 66 47 66
Leela Soft Python Madhu
The elements present in range Data type are not modifiable. i.e., range Data type is
immutable.
Form-1: range(10) : generate numbers from 0 to 9
Example:
>>>r=range(10)
>>>for i in r : print(i) #0 to 9
Form-2: range(10, 20) : generate numbers from 10 to 19
Example:
r = range(10,20)
for i in r : print(i) #10 to 19
Form-3: range(10,20,2) : generate numbers from 10 to 19 but with difference
by 2. Here 2 means increment value nothing but step.
Example:
r = range(10, 20, 2)
for i in r : print(i) # 10,12,14,16,18
We can access elements present in the range Data Type by using index.
r = range(10, 20)
r[0] # 10
r[15] # IndexError: range object index out of range
set Data Type:
If we want to represent a group of values without duplicates where order is not important then
we should go for set Data Type.
Example:
s = {100, 0, 10, 200, 10, 'Madhu'}
print(s) # {0, 100, 'Madhu', 200, 10}
dict Data Type:
If we want to represent a group of values as key-value pairs then we should go for dict data
type.
Example:
d={101:'durga',102:'Madhu',103:'shiva'}
www.leelasoft.com Cell: 78 42 66 47 66
Leela Soft Python Madhu
Duplicate keys are not allowed but values can be duplicated. If we are trying to insert an entry
with duplicate key then old value will be replaced with new value.
Example:
>>> d={101:'durga',102:'madhu',103:'shiva'}
>>> d[101]='sunny'
>>> d
101: 'sunny', 102: 'madhu', 103: 'shiva'}
We can create empty dictionary as follows
d={}
We can add key-value pairs as follows
d['a']='apple'
d['b']='banana'
print(d)
Operators in Python
Operator is a symbol that performs certain operations.
Python provides the following set of operators
1. Arithmetic Operators
2. Relational Operators or Comparison Operators
3. Logical operators
4. Bitwise operators
5. Assignment operators
6. Special operators
1. Arithmetic Operators:
+ ==>Addition
- ==>Subtraction
* ==>Multiplication
/ ==>Division operator
% ===>Modulo operator
// ==>Floor Division operator
www.leelasoft.com Cell: 78 42 66 47 66
Leela Soft Python Madhu
** ==>Exponent operator or power operator
Example 1: test.py:
a=10
b=2
print('a+b=',a+b)
print('a-b=',a-b)
print('a*b=',a*b)
print('a/b=',a/b)
print('a//b=',a//b)
print('a%b=',a%b)
print('a**b=',a**b)
Output:
python test.py or py test.py
a+b= 12
a-b= 8
a*b= 20
a/b= 5.0
a//b= 5
a%b= 0
a**b= 100
Example 2: test.py
a=10.5
b=2
print('a+b=', a+b)
print('a-b=', a-b)
print('a*b=', a*b)
print('a/b=', a/b)
print('a//b=', a//b)
print('a%b=', a%b)
print('a**b=', a**b)
Output:
python test.py or py test.py
a+b= 12.5
a-b= 8.5
a*b= 21.0
a/b= 5.25
a//b= 5.0
www.leelasoft.com Cell: 78 42 66 47 66
Leela Soft Python Madhu
a%b= 0.5
a**b= 110.25
Example 3: test.py
10 / 2 # 5.0
10 // 2 # 5
10.0 / 2 # 5.0
10.0 // 2 # 5.0
Note: / operator always performs floating point arithmetic. Hence it will always
return float value.
But Floor division (//) can perform both floating point and integral arithmetic. If
arguments are int type then result is int type. If at least one argument is
float type then result is float type.
Relational Operators:
>, >=, <, <=
Example:
a = 10
b = 20
print("a > b is ", a > b)
print("a >= b is ", a >= b)
print("a < b is ", a < b)
print("a <= b is ", a <= b)
We can apply relational operators for str types also
Example:
a = "madhu"
b = "madhuF"
print("a > b is ", a > b)
print("a >= b is ", a >= b)
print("a < b is ", a < b)
print("a <= b is ", a <= b)
Example:
print(True > True)
print(True >= True)
www.leelasoft.com Cell: 78 42 66 47 66
Leela Soft Python Madhu
print(10 > True)
print(False > True)
print(10>'durga')
TypeError: '>' not supported between instances of 'int' and 'str'
Note: Chaining of relational operators is possible. In the chaining, if all
comparisons return True then only result is True. If at least one comparison
returns False then the result is False.
Example:
print(10 < 20)
print(10 < 20 < 30)
print(10 < 20 < 30 < 40)
print(10 < 20 < 30 < 40 > 50)
Equality Operators:
== , !=
We can apply these operators for any type even for incompatible types also
>>> 10 == 20
False
>>> 10 != 20
True
>>> 10 == True
False
>>> False == False
True
>>> "madhu" == "madhu"
True
>>> 10 == "madhu"
False
Note: Chaining concept is applicable for equality operators. If at least one
comparison returns False then the result is False. otherwise the result is True.
>>>10 == 20 == 30 == 40
False
www.leelasoft.com Cell: 78 42 66 47 66
Leela Soft Python Madhu
>>>10 == 10 == 10 == 10
True
Logical Operators:
The logical operators are and, or, not. We can apply these operators for all
types.
For Boolean types behavior:
and : If both arguments are True then only result is True
or : If at least one argument is True then result is True
not : Complement i.e. True is False and False is True
Bitwise Operators:
We can apply these operators bitwise.
These operators are applicable only for int and Boolean types.
By mistake if we are trying to apply for any other type then we will get
Error.
The operators are &, |, ^, ~, <<, >>
& : If both bits are 1 then only result is 1 otherwise result is 0
| : If at least one bit is 1 then result is 1 otherwise result is 0
^ : If bits are different then only result is 1 otherwise result is 0
~ : bitwise complement operator 1 is 0 & 0 is 1
<< : Bitwise Left shift
>> : Bitwise Right Shift
Example:
print(4 & 5) #Valid
print(10.5 & 5.6)
#TypeError: unsupported operand type(s) for &: 'float' and 'float'
print(True & True) #Valid
www.leelasoft.com Cell: 78 42 66 47 66
Leela Soft Python Madhu
Example:
print(4 & 5)
print(4 | 5)
print(4 ^ 5)
Bitwise complement operator (~):
We have to apply complement for total bits.
Example:
print(~5) #-6
Note:
The most significant bit acts as sign bit. 0 value represents positive value whereas
1 represents negative value.
Positive numbers will be represented directly in the memory whereas negative
numbers will be
represented indirectly in 2's complement form.
Shift Operators:
<< Left shift operator:
After shifting the empty cells, we have to fill with zero.
Example:
print(10<<2) #40
>> Right Shift operator:
After shifting the empty cells, we have to fill with sign bit. (0 for positive
value and 1 for negative value).
www.leelasoft.com Cell: 78 42 66 47 66
Leela Soft Python Madhu
Example:
print(10>>2) #2
We can apply bitwise operators for Boolean types also
Example:
print(True & False) # False
print(True | False) # True
print(True ^ False) # True
print(~True) # -2
print(True << 2) # 4
print(True >> 2) # 0
Assignment Operators:
We can use assignment operator to assign value to the variable.
Example:
x = 0
We can combine assignment operator with some other operator to form
compound assignment operator.
Example:
x += 10 is equals to x = x + 10
The following is the list of all possible compound assignment operators in Python
+=, -=, *=, /=, %=, //=, **=
&=, |=, ^=, >>=, <<=
www.leelasoft.com Cell: 78 42 66 47 66
Leela Soft Python Madhu
Example:
x = 10
x += 20
print(x)
Example:
x = 10
x &= 5
print(x)
Ternary Operator:
Syntax:
x = firstValue if condition else secondValue
If condition is True then firstValue will be considered else secondValue
will be considered.
Example:
a, b = 10, 20
x = 30 if a < b else 40
print(x) #30
Example: Read two numbers from the keyboard and print minimum value
a = int(input("Enter First Number:"))
b = int(input("Enter Second Number:"))
min = a if a < b else b
print("Minimum Value:", min)
Output:
Enter First Number:10
Enter Second Number:30
Minimum Value: 10
Note: Nesting of ternary operator is possible.
Example: Program for minimum of 3 numbers
a = int(input("Enter First Number:"))
b = int(input("Enter Second Number:"))
www.leelasoft.com Cell: 78 42 66 47 66
Leela Soft Python Madhu
c = int(input("Enter Third Number:"))
min = a if a < b and a < c else b if b < c else c
print("Minimum Value:", min)
Example: Program for maximum of 3 numbers
a = int(input("Enter First Number:"))
b = int(input("Enter Second Number:"))
c = int(input("Enter Third Number:"))
max = a if a > b and a > c else b if b > c else c
print("Maximum Value:", max)
Example:
a = int(input("Enter First Number:"))
b = int(input("Enter Second Number:"))
print("Both numbers are equal" if a == b else "First Number is Less than
Second Number" if a < b else "First Number Greater than Second Number")
Special operators:
Python defines the following 2 special operators
1. Identity Operators
2. Membership operators
1. Identity Operators
We can use identity operators for address comparison.
2 identity operators are available. They are is, is not
r1 is r2 returns True if both r1 and r2 are pointing to the same object
r1 is not r2 returns True if both r1 and r2 are not pointing to the same
object
Example:
a = 10
b = 10
print(a is b) # True
x = True
y = True
print(x is y) # True
Example:
www.leelasoft.com Cell: 78 42 66 47 66
Leela Soft Python Madhu
a="madhu"
b="madhu"
print(id(a))
print(id(b))
print(a is b)
Example:
list1 = ["one", "two", "three"]
list2 = ["one", "two", "three"]
print(id(list1))
print(id(list2))
print(list1 is list2) # False
print(list1 is not list2) # True
print(list1 == list2) # True
Note:
We can use ‘is’ operator for address comparison whereas ‘==’ operator for
content comparison.
2. Membership operators:
We can use Membership operators to check whether the given object
present in the given collection. (It may be String, List, Set, Tuple or Dict).
2 membership operators are available. They are in, not in
in Returns True if the given object presents in the specified Collection
not in Returns True if the given object not present in the specified
Collection
Example:
x = "hello learning Python is very easy!!!"
print('h' in x) # True
print('d' in x) # False
print('d' not in x) # True
print('Python' in x) # True
Example:
list1 = ["sunny", "bunny", "chinny", "pinny"]
print("sunny" in list1) # True
print("tunny" in list1) # False
print("tunny" not in list1) # True
www.leelasoft.com Cell: 78 42 66 47 66
Leela Soft Python Madhu
www.leelasoft.com Cell: 78 42 66 47 66