Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
15 views

Python Notes Ch 1

Python is an open-source, high-level programming language that supports both object-oriented and procedure-oriented programming. It has a rich history dating back to the 1980s and offers features such as easy syntax, a robust standard library, and portability across platforms. Python is widely used for web development, data analysis, automation, and more, making it a versatile tool for programmers.

Uploaded by

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

Python Notes Ch 1

Python is an open-source, high-level programming language that supports both object-oriented and procedure-oriented programming. It has a rich history dating back to the 1980s and offers features such as easy syntax, a robust standard library, and portability across platforms. Python is widely used for web development, data analysis, automation, and more, making it a versatile tool for programmers.

Uploaded by

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

Python Programming Unit-1 Notes

CHAPTER 1- Python Introduction


What is Python?
• Python is an open source, dynamic, high-level and interpreted programming language. It
supports Object Oriented programming approach to develop applications. It is simple and
easy to learn and provides lots of high-level data structures.
• It is a general-purpose language; it means that it can be used to create a variety of different
programs and isn’t specialized for any specific problems.

History of Python
• Python laid its foundation in 1980s.

• The implementation of Python was started in December 1989 by Guido Van Rossum at CWI
(Centrum Wiskunde & Informatica) in Netherland.
• In February 1991, Guido Van Rossum published the labeled version 0.9.0 to alt.sources.
• In 1994, Python 1.0 was released with new features like lambda, map, filter, and reduce.
• In 2000, Python 2.0 was released with new features such as list comprehensions, garbage
collection, cycle detecting and Unicode support.
• On December 3, 2008, Python 3.0 (also called "Py3K") was released. It was designed to
rectify the fundamental flaw of the language.
• ABC programming language is said to be the predecessor of Python language, which was
capable of Exception Handling.

Python Features and Advantages:


• Easy to Code and Easy to Read
Python is easy to learn as compared to other programming languages. Its syntax is
straight forward and much the same as the English language. There is no use of the
semicolon or curly-bracket.
• Free and Open-Source
Python is developed under an OSI-approved open-source license. Hence, it is
completely free to use, even for commercial purposes. It doesn't cost anything to
download Python or to include it in your application.
• 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.
• 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
1
Python Programming Unit-1 Notes

compile Python because it is processed at runtime by the interpreter.


• Portable
Python is portable in the sense that the same code can be used on different machines.
Suppose you write a Python code on a Mac. If you want to run it on Windows or Linux
later, you don’t have to make any changes to it.
• Object-Oriented and Procedure-Oriented
A programming language is object-oriented if it focuses design around data and
objects, rather than functions and logic. On the contrary, a programming language is
procedure-oriented if it focuses more on functions (code that can be reused). One of the
critical Python features is that it supports both object-oriented and procedure-oriented
programming.
• 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.
• Expressive Language
Python can perform complex tasks using a few lines of code. A simple example, the hello
world program you simply type print("Hello World"). It will take only one line to execute, while
Java or C takes multiple lines.
• Support for GUI
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.
• Dynamically Typed
Many programming languages need to declare the type of the variable before runtime.
With Python, the type of the variable can be decided during runtime. This makes Python
a dynamically typed language.
• 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.

What is use of Python?


Python is commonly used for developing websites and software, task automation, data
analysis, and data visualization.

What can we do with Python?

1) Data analysis and machine learning


Python has become a staple in data science, allowing data analysts and other
professionals to use the language to conduct complex statistical calculations, create data visualizations,
build machine learning algorithms, manipulate and analyze data, and complete other data-related tasks.

2
Python Programming Unit-1 Notes

Python can build a wide range of different data visualizations, like line and bar graphs, pie
charts, histograms, and 3D plots. Python also has a number of libraries that enable coders to write
programs for data analysis and machine learning more quickly and efficiently, like TensorFlow and
Keras.

2) Web development
Python is often used to develop the back end of a website or application—the parts that a user
doesn’t see. Python’s role in web development can include sending data to and from servers,
processing data and communicating with databases, URL routing, and ensuring security. Python offers
several frameworks for web development. Commonly used ones include Django and Flask.

3) Automation or scripting
If you find yourself performing a task over and over again, you could work more efficiently
by automating it with Python. Writing code used to build these automated processes is called
scripting. In the coding world, automation can be used to check for errors across multiple files,
convert files, execute simple math, and remove duplicates in data.

4) Software testing and prototyping


In software development, Python can aid in tasks like build control, bug tracking, and testing.
With Python, software developers can automate testing for new products or features. Some
Python tools used for software testing include Green and Requestium.

5) Everyday tasks
Python isn't only for programmers and data scientists. Learning Python can open new
possibilities for those in less data-heavy professions, like journalists, small business owners, or social
media marketers. Python can also enable non-programmer to simplify certain tasks in their lives.
Here are just a few of the tasks you could automate with Python:
• Keep track of stock market or crypto prices
• Send yourself a text reminder to carry an umbrella anytime it’s raining
• Update your grocery shopping list
• Renaming large batches of files
• Converting text files to spreadsheets
• Randomly assign chores to family members
• Fill out online forms automatically

Python interpreter, extension & implementations


Computers cannot understand code in the way humans write it and hence, you need an
interpreter between the computer and the human written code. The job of the interpreter is to convert
the code into a format that computers can then understand and process.

The interpreter processes the code in the following ways:


• Processes the Python script in a sequence.

3
Python Programming Unit-1 Notes

• Compiles the code into a byte code format which is a lower-level language understood by the
computers.
• The Python Virtual Machine (PVM) perform over the instructions of low-level byte code to
run them one by one.
The Python script is saved with a .py extension which informs the computer that it is a Python
program script.

Python Installation
Unlike Windows, the Unix based operating systems such as Linux and Mac come with pre-
installed Python. Also, the way Python scripts are run in Windows and Unix operating systems
differ.

Installing Python on Windows takes a series of few easy steps.

Step 1 − Select Version of Python to Install


Python has various versions available with differences between the syntax and working of
different versions of the language. We need to choose the version which we want to use or need.

Step 2 − Download Python Executable Installer


On the web browser, in the official site of python www.python.org ,move to the Download
for Windows section.
All the available versions of Python will be listed. Select the version required by you and
click on Download.

Step 3 − Run Executable Installer


Run the installer. The installation process will take few minutes to complete.

Step 4 − Verify Python is installed on Windows


To ensure if python is successfully installed on your system.
Follow the given steps −
• Open the command prompt.
• Type ‘python’ and press enter.
• The version of the python which you have installed will be displayed if the python is
successfully installed on your windows.

Step 5 − Verify Pip was installed


Pip is a powerful package management system for Python software packages. Thus, make sure that
you have it installed.
To verify if pip was installed, follow the given steps −
• Open the command prompt.
• Enter pip –V to check if pip was installed.
• The following output appears if pip is installed successfully.
Note: For all users, especially Windows OS users, it is highly recommended that you install
Anaconda, which can be downloaded from https://www.anaconda.com/

4
Python Programming Unit-1 Notes

Python Program Execution

List out Different ways to run Python Script


Here are the ways with which we can run a Python script.
1. Interactive Mode –
We have to write code in command prompt line by line.
To enter in an interactive mode, you will have to open Command Prompt on your windows
machine and type ‘python’ and press Enter.

Run the following line one by one in the interactive mode:

a=1
b=3
if a > b:
print("a is Greater")
else:
print("b is Greater")

5
Python Programming Unit-1 Notes

On a Mac system, it is very straight-forward. All you need to do is open Launchpad and
search for Terminal, and in the terminal, type Python and boom, it will give you an output
with the Python version.
Like the Mac system, accessing terminal on a Linux system is also very easy. Right click on
the desktop and click Terminal and in terminal type Python and that's all!
2. Command Line –
We have to make python file first and save by .py extension. This file you can run in
command prompt by write python first and then your filename.
• Create a file having extension .py
• Write Python script in created file
• To run a Python script store in a ‘.py’ file in command line, write ‘python’ keyword
before the file name in the command prompt.

python hello.py

Note: You can write your own file name in place of ‘hello.py’.
# File Name:- hello.py
# File Path:- C:\Users\Anonymous\Desktop\GfG\hello.py
print ("Hello World!")

6
Python Programming Unit-1 Notes

3. Text Editor (Example:-Notepad++, VS Code, etc..)


4. IDE (Examples :- IDLE, Spyder, Atom, PyCharm, etc..)

Values and types:-


A value is one of the basic things a program works with, like a letter or a number.
A value may be characters i.e. ‘Hello, World!’ or a number like 1, 2.2, 0.9 etc.

To print the value print() function is used.

Example:-
>>> print('Hello, World!')
Hello, World!
>>> print(1)
1
>>> print(2.2)
2.2
>>> print('Abc@123')
Abc@123

type( ):- To find the type of given value type() function is used.
In python we don’t have to write int, float, char it will automatically understand the type of
given value. So, if we want to find particular type of given value, we can use the type function.

Example:- >>> type('Hello, World!')


<class 'str'>
>>> type(1)
<class 'int'>
>>> type(2.2)
<class 'float'>
>>> print(''Abc@123'')
<class 'str'>

Variables
Variables are containers for storing data values.

Creating Variables
1. Python has no command for declaring a variable. We just have to write variable name
and assign the value in it.
2. A variable is created the moment you first assign a value to it.

Example:- Output:-
x=5
y = “LJ Polytechnic” 5
print(x) LJ Polytechnic
print(y)
7
Python Programming Unit-1 Notes

3. Variables do not need to be declared with any particular type, and can even change
type after they have been set. If we use the same name, the variable starts referring to
a new value and type.
Example:- Output:-
x=5
LJ Polytechnic
x = “LJ Polytechnic”
print(x)
4. Python allows assigning a single value to several variables simultaneously with “=”
operators.
Example:-
x = y = z = 100 Output:- 100
print(y)

5. Assigning different values to multiple variables:


Python allows adding different values in a single line with “,”operators.
Example:-
a, b, c = 1, 2.2, 'ABC' Output:-
print(a) 1
print(b) 2.2
print(c) ABC

6. How does + operator work with variables?


Example:- Output:-
a = 10
30
b = 20
LJKU
print(a+b)
x = 'LJ'
y = 'KU'
print(x+y)

Can + Operator work with different type variable?


No it can throw an error.
Example:- Output:-
a = 10 TypeError: unsupported operand
b = 'LJ' type(s) for +: 'int' and 'str'
print(a+b)

8
Python Programming Unit-1 Notes

Rules for creating variables in Python:


1. A variable name must start with a letter or the underscore character.
2. A variable name cannot start with a number.
3. A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9,
and _).
4. Variable names are case-sensitive (name, Name and NAME are three different variables).
5. The reserved words (keywords) cannot be used to naming the variable.
The interpreter uses keywords to recognize the structure of the program, and they cannot be used
as variable names. Python reserves 35 keywords:

Keywords:-
and del from none true continue lambda

as elif global nonlocal try def is

assert else if not while finally return

break except in or with for async

class false import pass yield raise wait

String:
• Strings are arrays of bytes representing Unicode characters.
• String data type is most important data type in python.
• Python does not have a character data type, a single character is simply a string with a length
of 1.
• String is not a small. It can also big as million characters.
• Python has also built in functions and algorithms for string.
• String is the combination of multiple characters.
• String index is starting from 0.

Example:- Output:-
s = 'P' P
print(s) <class ‘str’>
type(s) Python
<class ‘str’>
language = 'Python'
print(language)
type(language)

9
Python Programming Unit-1 Notes

[0] [1] [2] [3] [4] [5]

String:- P y t h o n
[-6] [-5] [-4] [-3] [-2] [-1]

• Square brackets can be used to access elements of the string.


Example:- Output:-
language = 'Python'
letter = language[1] y
print(letter) P
n
print(language[0]) TypeError: string indices must be
print(language[-1]) integers
print(language[1.5])

Length of a string:
• To find the length of the string len( ) function is used.
• len() is a built-in function that returns the number of characters in a string:
Example:- Output:-
language = 'Python' 6
print( len(language))

• To get the last letter of a string, you might be tempted to try something like this:
Because if you write simply length, then length will start from 0 so it can’t display last digit.

x = "Python"
length = len(x) n
y=x[length-1]
print(y)

String slices:
A segment of a string is called a slice. Selecting a slice is similar to selecting a character:

We can specify start, stop and step (optional) within the square brackets as:
string[start:stop:step]

• start: It is the index from where the slice starts. The default value is 0.
• stop: It is the index at which the slice stops. The character at this index is not included in the
slice. The default value is the length of the string.
• step: It specifies the number of jumps to take while going from start to stop. It takes the
default value of 1.

10
Python Programming Unit-1 Notes

Example:-

s = 'Welcome to LJKU'
print(s[0:8])
print(s[11:16])

#bydefault starting index is "0" and middle index in "lenght of string"


print(s[:])
print(s[0:])

#if we can write same digit at both place then it will not give us any output
print(s[3:3])

#Replace any latter with any index of given string.


r = 'J' + s[1:]
print(r)

#if we write -1 at step place it will give output as reverse of string


print(s[ : :-1])

#For step jumping


print(s[0: :2])#it will give output as skip 1 character from starting of string

print(s[ : :-2]) #it will first reverse the string and skip 1 character after reverse.

Output:-
Welcome
LJKU
Welcome to LJKU
Welcome to LJKU

Jelcome to LJKU
UKJL ot emocleW
Wloet JU
UJ teolW

String methods
Everything in Python is an object. A string is an object too. Python provides us with various methods
to call on the string object.
Note: Note that none of these methods alters the actual string. They instead return a copy of the
string. This copy is the manipulated version of the string.
11
Python Programming Unit-1 Notes

capitalize( )
This method is used to capitalize a string.

>>>s = 'heLlo pYthOn'


>>> s2 = s.capitalize()
>>> print(s2)
Hello python

lower( )
This method converts all alphabetic characters to lowercase.

>>>s = 'heLlo pYthOn'


>>> s2 = s.lower()
>>> print(s2)
hello python

upper( )
This method converts all alphabetic characters to uppercase.

>>>s = 'heLlo pYthOn'


>>> s2 = s.upper()
>>> print(s2)
HELLO PYTHON

title( )
This method converts the first letter of each word to uppercase and remaining letters to
lowercase

>>>s = 'heLlo pYthOn'


>>> s2 = s.title()
>>> print(s2)
Hello Python

swapcase([<chars>])
This method swaps case of all alphabetic characters.

>>>s = 'HeLlo PyThOn'


>>> s2 = s.swapcase ()
>>> print(s2)
hElLO pYtHoN
12
Python Programming Unit-1 Notes

count(<sub>, <start>, <end>)


This method returns the number of time <sub> occurs in string.

>>>s = 'Python Programming'


>>>s.count('P')
2
>>>s.count('mm')
1
>>>s.count('P',3,10)
1

find(<sub>, <start>, <end>)


This method returns the index of the first occurrence of <sub> in s. Returns -1 if the substring is not
present in the string.

>>>s = 'Python Programming'


>>>s.find('Pro')
7
>>>s.find('on',3,10)
4
lstrip( )
This method removes leading characters from a string. Removes leading whitespaces if you don’t
provide a <chars> argument.

>>>s = ' Python '


>>>s.lstrip()
'Python '

rstrip( )
This method removes trailing characters from a string. Removes trailing whitespaces if you don’t
provide a <chars> argument.

>>>s = ' Python '


>>>s.rstrip()
' Python'

strip( )
This method removes leading and trailing characters from a string. Removes leading and
trailing whitespaces if you don’t provide a <chars> argument

>>>s = ' Python '


>>>s.strip() 13
'Python'
Python Programming Unit-1 Notes

join(<iterable>)
This method returns the string concatenated with the elements of iterable.

>>>s=('We','are','coders')
>>>s1= '_'.join(s)
print(s1)
We_are_coders

split(sep=None, maxsplit=-1)
This method splits a string into a list of substrings based on sep. If you don’t pass a value to sep, it
splits based on whitespaces.

>>>s = 'Python Programming'


>>>s.split()
['Python', 'Programming']
>>>s = 'Python Programming'
>>>s.split('o')
['Pyth', 'n Pr', 'gramming']

Strings can be concatenated (glued together) with the + operator, and repeated with *:

>>>3*'un'
'ununun'
>>>'Py''thon'
'Python'
>>>'Py'+'thon'
'Python'

Escape Characters
To insert characters that are illegal in a string, use an escape character. An escape character is a
backslash (\) followed by the character you want to insert.

>>>s = ''we are the so-called ''Vikings'' from the north''


SyntaxError: invalid syntax

To fix this problem, use the escape character \"

>>>s = ''we are the so-called \''Vikings\'' from the north''


'we are the so-called ''Vikings'' from the north'

14
Python Programming Unit-1 Notes

List of escape sequences available in Python 3:


Code Result Code Result

\' Single Quote \t Tab

\\ Backslash \b Backspace

\n New Line \f Form Feed

\r Carriage Return \ooo Octal value

\xhh Hex value

Numbers
There are three numeric types in Python:
• int
• float
• complex
Variables of numeric types are created when you assign a value to them:

>>>x = 1 #int
>>> y = 2.8 #float
>>> z = 1j #complex
>>>print(type(x))
<class 'int'>
>>>print(type(y))
<class 'float'>
>>>print(type(z))
<class 'complex'>
Int
Integer is a whole number, positive or negative, without decimals, of unlimited length.

>>>x = 1
>>>y = 35656222554887711
>>>z = -3255522
>>>print(type(x))
<class 'int'>
>>>print(type(y))
<class 'int'>
>>>print(type(z)) 15
<class 'int'>
Python Programming Unit-1 Notes

Float
Float or "floating point number" is a number, positive or negative, containing one or more decimals.
Float can also be scientific numbers with an "e" to indicate the power of 10.

>>>x = 1.10 >>>x = 35e3


>>>y = 1.0 >>>y = 12E4
>>>z = -35.59 >>>z = -87.7e100
>>>print(type(x)) >>>print(type(x))
<class 'float'> <class 'float'>
>>>print(type(y)) >>>print(type(y))
<class 'float'> <class 'float'>
>>>print(type(z)) >>>print(type(z))
<class 'float'> <class 'float'>

Complex
Complex numbers are written with a "j" as the imaginary part:

x = 3+5j
y = 5j
z = -5j <class 'complex'>
<class 'complex'>
print(type(x))
<class 'complex'>
print(type(y))
print(type(z))

Type Conversion
You can convert from one type to another with the int(), float(), and complex() methods
Example:-

x = 1 # int Output:-
y = 2.8 # float
z = 1j # complex
#convert from int to float:
a = float(x) 1.0
#convert from float to int: <class 'float'>
b = int(y) 2
#convert from int to complex: <class 'int'>
c = complex(x) (1+0j)
print(a) <class 'complex'>
print(type(a))
print(b)
print(type(b))
print(c) 16
print(type(c))
Python Programming Unit-1 Notes

Operators
Operators in general are used to perform operations on values and variables. These are
standard symbols used for the purpose of logical and arithmetic operations.
Arithmetic Operators
Arithmetic operators are used to performing mathematical operations like addition,
subtraction, multiplication, and division.

Operator Description Syntax

+ Addition: adds two operands x+y

- Subtraction: subtracts two operands x–y

* Multiplication: multiplies two operands x*y

/ Division (float): divides the first operand by the x / y


second

// Division (floor): divides the first operand by the x // y


second

% Modulus: returns the remainder when the first x % y


operand is divided by the second

** Power: Returns first raised to power second x ** y

Example:- Output:-
a = 21
b = 10
c=0
c=a+b
print("Addition is:-",c)
c=a-b Addition is:- 31
print('Subtraction is:-',c) Subtraction is:- 11
c=a*b Multiplication is:- 210
print('Multiplication is:-',c) Division is:- 2.1
c=a/b Reminder of a/c is:- 1
print('Division is:-',c) result of p^q is:- 8
c=a%b result of a devide b is:- 2
print("Reminder of a/c is:-",c)
p=2
q=3
r =p**q
print("result of p^q is:-",r)
x = 11
y=5
17
z = a//b
print("result of a devide b is:-",z)
Python Programming Unit-1 Notes

Comparison Operators
Comparison of Relational operators compares the values. It either returns True or False
according to the condition.

Operator Description Syntax

> Greater than: True if the left operand is greater than x > y
the right

< Less than: True if the left operand is less than the x < y
right

== Equal to: True if both operands are equal x == y

!= Not equal to – True if operands are not equal x != y

>= Greater than or equal to True if the left operand is x >= y


greater than or equal to the right

<= Less than or equal to True if the left operand is less x <= y
than or equal to the right
Example:

>>># Examples of Relational Operators


>>>a, b = 13, 33

>>># a > b is False


>>>print(a > b)
False

>>># a < b is True


>>>print(a < b)
True

>>># a == b is False
>>>print(a == b)
False

>>># a != b is True
>>>print(a != b)
True

18
Python Programming Unit-1 Notes

Logical Operators
Logical operators perform Logical AND, Logical OR, and Logical NOT operations. It is used
to combine conditional statements.

Operator Description Syntax

and Logical AND: True if both the operands are true x and y

or Logical OR: True if either of the operands is true x or y

not Logical NOT: True if the operand is false Not x

Example: Output:
x=5
False
print(x>3 and x>10) #and
True
print (x>3 or x>10) #or
True
print(not(x > 3 and x > 10))
# returns False because not is used to reverse the result

Bitwise Operators
Bitwise operators act on bits and perform the bit-by-bit operations. These are used to operate on
binary numbers.
Operator Description Syntax

& Operator copies a bit to the result if it exists in both x & y


Bitwise AND operands (means 0000 1100)

| It copies a bit if it exists in either operand. x | y = 61 (means


Bitwise OR 0011 1101)

~ It copies the bit if it is set in one operand but not ~x


Bitwise NOT both.

^ It is unary and has the effect of 'flipping' bits. x^y


Bitwise XOR

>> The left operands value is moved left by the number x>>
Bitwise right of bits specified by the right operand.
shift

<< The left operands value is moved right by the x<<


Bitwise left number of bits specified by the right operand.
shift

19
Python Programming Unit-1 Notes

Example: Output:

>>># Examples of Bitwise operators


a = 60 # 60 = 0011 1100
b = 13 # 13 = 0000 1101
Answer of a & b is:- 12
c=0
Answer of a | b is:- 61
Answer of a ^ b is:- 49
c=a&b # 12 = 0000 1100
Answer of ~60 is:- -61
print('Answer of a & b is:-',c)
Answer of a<<2 is:- 240
Answer of a>>2 is:- 15
c=a|b # 61 = 0011 1101
>>>
print('Answer of a | b is:-',c)

c=a^b # 49 = 0011 0001


print('Answer of a ^ b is:-',c)

c = ~a # -61 = 1100 0011


print('Answer of ~60 is:-',c)

c = a << 2 # 240 = 1111 0000


print('Answer of a<<2 is:-',c)

c = a >> 2 # 15 = 0000 1111


print('Answer of a>>2 is:-',c)

Assignment Operators
Assignment operators are used to assigning values to the variables.

Operator Description Syntax

= Assign value of right side of expression to left side x = y + z


operand

+= Add AND: Add right-side operand with left side a +=b


operand and then assign to left operand a=a+b

-= Subtract AND: Subtract right operand from left a -=b


operand and then assign to left operand a=a - b

*= Multiply AND: Multiply right operand with left a *=b


operand and then assign to left operand a=a * b

20
Python Programming Unit-1 Notes

/= Divide AND: Divide left operand with right operand a /=b


and then assign to left operand a=a / b

%= Modulus AND: Takes modulus using left and right a %=b


operands and assign the result to left operand a=a % b

//= Divide(floor) AND: Divide left operand with right a /=b


operand and then assign the value(floor) to left a=a // b
operand

**= Exponent AND: Calculate exponent(raise power) a **=b


value using operands and assign value to left operand a=a ** b

&= Performs Bitwise AND on operands and assign value a &=b


to left operand a=a&b

|= Performs Bitwise OR on operands and assign value to a |=b


left operand a=a | b

^= Performs Bitwise XOR on operands and assign value a ^=b


to left operand a=a ^ b

>>= Performs Bitwise right shift on operands and assign a >>=b


value to left operand a=a>>b

<<= Performs Bitwise left shift on operands and assign a <<=b


value to left operand a=a<<b

Identity Operators
is and is not are the identity operators both are used to check if two values are located on
the same part of the memory. Two variables that are equal do not imply that they are identical.

Operator Description

is True if the operands are identical

is not True if the operands are not identical

>>> a = 10
>>> b = 20
>>> c = a

>>> print(a is not b)


True
>>> print(a is c)
True
21
Python Programming Unit-1 Notes

Membership Operators

in and not in are the membership operators; used to test whether a value or variable is in a
sequence.

Operator Description

in True if value is found in the sequence

in not True if value is not found in the sequence

Example:-

#membership_ex.py
x = 24
y = 20
list = [10, 20, 30, 40, 50]

if (x not in list):
print("x is NOT present in given list")
else:
print("x is present in given list")

if (y in list):
print("y is present in given list")
else:
print("y is NOT present in given list")

Output:-

x is NOT present in given list


y is present in given list

22
Python Programming Unit-1 Notes

Precedence and Associativity of Operators


Operator precedence and associativity determine the priorities of the operator.
Operator Precedence
This is used in an expression with more than one operator with different precedence to determine
which operation to perform first.

>>> # Precedence of '+' & '*'


>>> expr = 10 + 20 * 30
>>> print(expr)
610

>>> # Precedence of 'or' & 'and'


>>> name = "Alex"
>>> age = 0

>>> if name == "Alex" or name == "John" and age >= 2:


... print("Hello! Welcome.")
. . . else:
... print("Good Bye!!")
Hello! Welcome.

Operator Associativity
If an expression contains two or more operators with the same precedence then Operator
Associativity is used to determine. It can either be Left to Right or from Right to Left.

23

You might also like