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

Unit 1

Uploaded by

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

Unit 1

Uploaded by

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

UNIT I – INTRODUCTION TO

PYTHON PROGRAMMING
UNIT-I INTRODUCTION TO PYTHON
PROGRAMMING
Introduction to Python Programming – Python Interpreter and
Interactive Mode – Variables and Identifiers – Arithmetic Operators–
Values and Types – Statements - Operators – Boolean Values –
Operator Precedence – Expression - Conditionals: if, if-else, if elif else
Constructs
What is Python?

Python is a popular programming language. It was


created by Guido van Rossum, and released in 1991.
It is used for:
•web development (server-side),
•software development,
•mathematics,
•system scripting.
What can Python do?

• Python can be used on a server to create web


applications.
• Python can be used alongside software to create
workflows.
• Python can connect to database systems. It can also
read and modify files.
• Python can be used to handle big data and perform
complex mathematics.
• Python can be used for rapid prototyping, or for
production-ready software development.
Why Python?

• Python works on different platforms (Windows, Mac, Linux,


Raspberry Pi, etc).
• Python has a simple syntax similar to the English language.
• Python has syntax that allows developers to write programs
with fewer lines than some other programming languages.
• Python runs on an interpreter system, meaning that code
can be executed as soon as it is written. This means that
prototyping can be very quick.
• Python can be treated in a procedural way, an
object-oriented way or a functional way.
Python Syntax compared to other
programming languages
• Python was designed for readability, and has some
similarities to the English language with influence from
mathematics.
• Python uses new lines to complete a command, as
opposed to other programming languages which often
use semicolons or parentheses.
• Python relies on indentation, using whitespace, to
define scope; such as the scope of loops, functions and
classes. Other programming languages often use
curly-brackets for this purpose.
Example

print("Hello, World!")
Python Interpreter
• The Python interpreter can runPython programs that
are saved infiles, or can interactively executePython
statements that are typedat the keyboard. Python
comeswith a program named IDLE thatsimplifies the
process of writing,executing, and testing programs.
Python Interpreter
• The Python Interpreter
• •A program that can read Python programming statements
andexecute them is thePython interpreter
• •Python interpreter has two modes:
• –Interactivemode waits for a statement from the keyboard and executes it
• –Scriptmode reads the contents of a file (Python programorPython script) and
interprets each statement in the file
Python Interpreter
• Interpreter Mode
•Invoke Python interpreter through Windows or command line
•>>>is the prompt that indicates the interpreter is waiting for aPython
statement

>>>print ‘Python programming is fun!’Python programming is fun!


>>>

•Statements typed in interactive mode are not saved as a program


Python Interpreter
Writing Python Programs and Running Them inScript
Mode
•Use a text editor to create a file containing the Pythonstatements
•Save the file with a.pyextension
•To run the program:

>>>python test.py
Python Variables

• Variable is a name that is used to refer to memory location.


Python variable is also known as an identifier and used to
hold value.
• In Python, we don't need to specify the type of variable
because Python is a infer language and smart enough to
get variable type.
• Variable names can be a group of both the letters and
digits, but they have to begin with a letter or an underscore.
• It is recommended to use lowercase letters for the variable
name. Rahul and rahul both are two different variables.
Identifier Naming

• Variables are the example of identifiers. An Identifier is used to identify the


literals used in the program. The rules to name an identifier are given below.
• The first character of the variable must be an alphabet or underscore ( _ ).
• All the characters except the first character may be an alphabet of
lower-case(a-z), upper-case AZ, underscore, or digit 09.
• Identifier name must not contain any white-space, or special character !, @,
#, %, ^, &, *).
• Identifier name must not be similar to any keyword defined in the language.
• Identifier names are case sensitive; for example, my name, and MyName is
not the same.
• Examples of valid identifiers: a123, _n, n_9, etc.
• Examples of invalid identifiers: 1a, n%4, n 9, etc.
Declaring Variable and Assigning Values

• Python does not bind us to declare a variable before using it


in the application. It allows us to create a variable at the
required time.
• We don't need to declare explicitly variable in Python. When
we assign any value to the variable, that variable is declared
automatically.
• The equal (=) operator is used to assign value to a variable.
Object References

• It is necessary to understand how the Python interpreter works when we


declare a variable. The process of treating variables is somewhat different
from many other programming languages.
• Python is the highly object-oriented programming language; that's why
every data item belongs to a specific type of class. Consider the following
example.
print("John")
Output:
John
• The Python object creates an integer object and displays it to the console. In
the above print statement, we have created a string object. Let's check the
type of it using the Python built-in type() function.
type("John")
Output: <class 'str'>
• In Python, variables are a symbolic name that is a reference or
pointer to an object. The variables are used to denote objects by
that name.
a = 50

Suppose we assign the integer value 50 to a new variable b.


• a = 50
•b=a
Variable Names

• Variable names can be any length can have uppercase, lowercase A to Z, a to z),
the digit 09, and underscore character(_). Consider the following example of valid
variables names.
• Example
name = "A"
Name = "B"
naMe = "C"
NAME = "D"
n_a_m_e = "E"
_name = "F"
name_ = "G"
_name_ = "H"
na56me = "I"
• The multi-word keywords can be created by the following
method.
• Camel Case - In the camel case, each word or abbreviation
in the middle of begins with a capital letter. There is no
intervention of whitespace. For example - nameOfStudent,
valueOfVaraible, etc.
• Pascal Case - It is the same as the Camel Case, but here
the first word is also capital. For example - NameOfStudent,
etc.
• Snake Case - In the snake case, Words are separated by
the underscore. For example - name_of_student, etc.
Multiple Assignment

• Python allows us to assign a value to multiple variables in a single


statement, which is also known as multiple assignments.
• Eg -1. Assigning single value to multiple variables
x=y=z=50
print(x)
print(y)
print(z)
• Eg 2. Assigning multiple values to multiple variables:
a,b,c=5,10,15
print (a)
print (b)
print (c)
Python Variable Types
• There are two types of variables in Python - Local variable and Global variable. Let's understand the following variables.
• Local Variable
• Local variables are the variables that declared inside the function and have scope within the function. Let's understand the following example.
# Declaring a function
def add():
# Defining local variables. They has scope only within a function
a = 20
b = 30
c=a+b
print("The sum is:", c)

# Calling a function
add()

Output
The sum is: 50
Global Variables
• Global variables can be used throughout the program, and its scope is in the entire program. We can use global variables inside or outside the function.
• A variable declared outside the function is the global variable by default. Python provides the global keyword to use global variable inside the function. If
we don't use the global keyword, the function treats it as a local variable. Let's understand the following example.
# Declare a variable and initialize it
x = 101

# Global variable in function


def mainFunction():
# printing a global variable
global x
print(x)
# modifying a global variable
x = 'Welcome To Javatpoint'
print(x)

mainFunction()
print(x)
101 Welcome To Javatpoint Welcome To Javatpoint

• Output:
101
Welcome To Javatpoint
Welcome To Javatpoint
Delete a variable

• We can delete the variable using the del keyword. The syntax is
given below.

del <variable_name>
Eg
# Assigning a value to x
x=6
print(x)
# deleting a variable.
del x
print(x)
VARIABLES
• A variable is a location in memory used to store some data (value).
They are given unique names to differentiate between different
memory locations.
• Variable names can be of any length. They can include both letters
and numbers, but they can’t begin with a number. It is legal to use
uppercase letters, but it is conventional to use only lower case for
variables names.
• The underscore character, _, can appear in a name. It is often used in
names with multiple words, such as your_name , air_speed, etc.
• Keywords cannot be used as variable names.
• Example:
• a, read_a, b1 etc
VALUES AND TYPES: INT, FLOAT, BOOLEAN,
STRING, AND LIST
• A value is one of the basic thing to work with a program like a letter or
a number. Some values are 2, 42.0, and 'Hello, World!'.
• These values belong to different types: 2 is an integer, 42.0 is a
floating-point number, and 'Hello, World!' is a string.
INT:
• Integers represent negative and positive integers without fractional
parts.
• >>> type(2)
• <class 'int'>
FLOAT:
Floating point numbers represents negative and positive numbers
with fractional parts
>>> type(42.0)
<class 'float'>
• BOOLEAN:
• The simplest built-in type in Python is the bool type, it represents
the truth values,(True or False)
>>> type(True)
<class 'bool'>
>>> type(False)
<class 'bool'>
STRING:
• A string type object is a sequence (left-to- right order) of characters.
Strings start and end with single or double quotes. Python strings are
immutable (Once a string is generated, you can not change any
character within the string).
LIST:
>>> type('Hello, World!')
<class 'str'>
A list is a container which holds comma-separated values (items or
elements) between square brackets where all the items or elements
need not to have the same type.
• A list without any element is called an empty list.
>>>list = [ 'abcd', 786 , 2.23, 'name', 70.2 ]
>>> print (list)
[ 'abcd', 786 , 2.23, 'name', 70.2 ]
>>>list1=[ ]
>>>print(list1)
[]
EXPRESSIONS AND STATEMENTS:

• An expression is a combination of values, variables, and operators. A


value itself can also be considered as an expression, and a variable
can also be considered as an expression.
• The following are all legal expressions:
>>> 42
42
>>> n=17
17
>>> n + 25
42
• When an expression is typed in the prompt, the interpreter evaluates
it, which means that it finds the value of the expression.
• In this example, n has the value 17 and n + 25 has the value 42.
• A statement is a unit of code that has an effect, like creating a
variable or displaying a value.
>>> n = 17
>>> print(n)
• The first line is an assignment statement that gives a value to n. The
second line is a print statement that displays the value of n.
• When a statement is typed in the prompt, the interpreter executes it,
which means that it does whatever the statement says. In general,
statements don’t have values.
Boolean Values

• A boolean expression is an expression that is either True


or False.
• Type bool includes two values - True and False.
• Example
>>> type(True)
<class 'bool'>
>>> type(False)
<class 'bool'>
• The = =(equal to) operator is one of the relational
operators. The operator = = compares two operands and
returns True if they are equal otherwise it returns False.
• Example
>>> 5 = = 5
True
>>> 5 = = 6
False
PRECEDENCE OF OPERATORS:

• When an expression contains more than one operator, the order of


evaluation depends on the order of operations or precedence of
operators. For mathematical operators, Python follows mathematical
convention. The acronym PEMDAS is a useful way to remember the
rules:
• Parentheses have the highest precedence and can be used to force an
expression to
• evaluate in the order you want. Since expressions in parentheses are
evaluated first, Example: 2 * (3-1) is 4, and (1+1)**(5-2) is 8.
• Parentheses can be used to make an expression easier to read.
• Example: (minute * 100) / 60, even if it doesn’t change the result.
• Exponentiation(**) has the next highest precedence, so Example : 1
+ 2**3 is 9 and 2 *3**2 is 18
• Multiplication and Division have higher precedence than Addition and
Subtraction.
• Example: 2*3-1 is 5 and 6+4/2 is 8.
• Operators with the same precedence are evaluated from left to right
(except exponentiation).
• Example: In the expression, degrees / 2 * pi, the division happens first
and the result is multiplied by pi.
CONDITIONAL (IF)

• Conditional statements are used to check conditions and change the


flow of the program execution accordingly.
• Syntax:
if booleanexpression:
statements
• The boolean expression after if is called the condition. If it is true, the
indented statement runs. If not, nothing happens.
• if statements have the same structure as function definitions- a
header followed by an indented body. Statements like this are called
compound statements.
• There should be one or more statements in body section.
Program
• x=int(input(“Enter a number”)) if(x>0):
• print(“Positive Number”)
Output:
• Enter a number 3
• Positive Number
ALTERNATIVE (IF-ELSE)

• A second form of the if statement is “alternative execution”, in which


there are two possibilities.
• Syntax
if booleanexpression:
Statements-1
else:
Statements-2
• Since the condition must be either True or False, exactly one of the
alternatives will be executed. The alternatives are also called as
branches.
If the condition is True, first set of statements will be executed and if
the condition is false, the second set of statements will be executed.
Program:
x=int(input(“Enter a number”)) if x % 2 == 0:
print(“Given number is even”)
else:
print(“Given number is odd”)
Output:
Enter a year 2
Given number is even
• When x is divided by 2 and if the remainder is 0, then it prints x is
even, otherwise it prints x is odd.
CHAINED CONDITIONAL (IF-ELIF-ELSE):
• If there are more than two possibilities, more than two branches is
needed, so chained conditional is used.
• Syntax
if booleanexpression1:
Statements-1
elif booleanexpression2:
Statements-2
else:
Statements-3
• elif is an abbreviation of “else if”. Again, exactly one branch will be
executed.
• There is no limit on the number of elif statements. If there is an else
clause, it should be at the end.
• Example
if choice == 'a':
draw_a()
elif choice == 'b':
draw_b()
elif choice == 'c':
draw_c()
• Each condition is checked in order. If the first condition is false, then
the next condition is checked, and so on. If one of them is True, the
corresponding branch runs and the statement ends. Even if more than
one condition is True, only the first true branch runs.
Program:
x=int(input(“Enter the value of x”)
y=int(input(“Enter the value of y”)
if x < y:
print(“x is less than y”)
elif x > y:
print(“x is greater than y”)
else:
print(“x and y are equal”)
Output:
Enter the value of x
5
Enter the value of y
4
x is greater than y
Nested conditionals

• Conditionals can be nested within another.


• Syntax
if booleanexpression1:
Statements-1
else:
if booleanexpression2:
Statements-2
else:
Statements-3
• Nested conditionals can hold one or more if..else statements within
another if..else statements.
• Logical operators provide a way to simplify nested conditional
statements.
• Example
if x>0:
if x < 10:
print('x is a positive single-digit number.')
• The print statement runs only if both conditionals are True, so logical
and operator can be used. The code can be written as
if x>0 and x < 10:
print('x is a positive single-digit number.')
• Python provides a more concise option for this kind of condition, :
if 0 < x < 10:
print('x is a positive single-digit number.')
Program:
x=int(input(“Enter the value of x”)
y=int(input(“Enter the value of y”)
if x == y:
print(“x and y are equal”)
else:
if x < y:
print(“x is less than y”)
else:
print(“x is greater than y”)
Output:
Enter the value of x
5
Enter the value of y
4
x is greater than y
FIRST PYTHON PROGRAM

 Execute the programs in different


modes.
 Interactive Mode Programming
 Script Mode Programming

2
INTERACTIVE MODE PROGRAMMING

 Once Python is
installed,
typing
will python
invoke theininterpreter
the command
in
immediate mode. line
 We can directly typein
Python
code, and press Enter to get
the output.
This prompt can be used
as a calculator.
To exit this mode, type quit()
and press enter.
For example,
3
SCRIPT MODE PROGRAMMING - IDE
 IDE - Integrated Development Environment
 When you install Python, an IDE named IDLE is also installed
 We can use any text editing software to write a Python
script file.
 When you open IDLE, an interactive Python Shell is opened.
 Now you can create a new file and save it
with .py extension.
 Write Python code in the file and save it.
 To run the file, go to Run > Run Module or simply click F5.
 For example,

4
PYTHON KEYWORDS

 Keywords are the reserved


False await else import pass
words in Python.
None break except in raise
 We cannot use a keyword
as a variable name, True class finally is return
function name or any other and continue for lambda try
identifier.
as def from nonlocal while
 In Python, keywords are
assert del global not with
case sensitive.
async elif if or yield

5
RULES FOR WRITING IDENTIFIERS

1. Identifiers can be a combination of letters in lowercase (a to z) or


uppercase (A to
Z) or digits (0 to 9) or an underscore _.
2. An identifier cannot start with a digit.
3. Keywords cannot be used as identifiers.
4. We cannot use special symbols in identifiers.
5. An identifier can be of any length.
6. Python is a case-sensitive language.
7. Multiple words can be separated using an underscore.
6
PYTHON STATEMENT

▪ Instructions that a Python interpreter can execute are called


statements.

Multi-line statement
▪ The end of a statement is marked by a newline character (\).
a=1+2+3+\
4+5+6+\
7+8+9
▪ Multiple statements in a single line using semicolons.
a = 1; b = 2; c = 3
7
CONTINUATION…

 Python does not use braces({}) to indicate blocks of code for class and
function definitions or flow control.
 Blocks of code are denoted by line indentation, which is rigidly
enforced.
 For example −
if True:
print ("True")
else:
8
print ("False")
PYTHON COMMENTS

 We use the hash (#) symbol to start writing a comment.

 All characters after the #, up to the end of the physical line, are part of the
comment and the Python interpreter ignores them.

# First comment
print (“Welcome to college!") # second comment This produces the following
result −

Welcome to college!
9
QUOTATION IN PYTHON

 Python accepts single ('), double (") and triple (''' or """) quotes to denote string literals, as
long as the same type of quote starts and ends the string.
 The triple quotes are used to span the string across multiple lines.
 For example,
word = 'word'
sentence = "This is a sentence." paragraph = """This is a paragraph. It is

made up of multiple lines and sentences."""

10
CLEAR WINDOWS

 >>> import os
 >>> clear =
os.system("cls")

11
STANDARD DATA TYPES

 The data stored in memory can be of many types.


 Python has various standard data types that are used to define the operations possible on
them and the storage method for each of them.
 Python has five standard data types −
 Numbers
 String
 List
 Tuple
 Dictionary
12
PYTHON - NUMBERS
 Number data types store numeric values.
 Number objects are created when you assign a value to
them.
 For example,
>>> abc=10
>>> xyz=150
>>> abc 10

>>> xyz
13

15
PYTHON - NUMBERS

 You can also delete the reference to a number object by using the del
statement.
 You can delete a single object or multiple objects by using the del
statement.
For example,
>>> del abc
>>> abc
Traceback (most recent call last): File "<stdin>", line 1, in <module>
NameError: name 'abc' is not defined
>>> xyz 150
>>> aa=9
>>> bb=5
>>> aa 9

>>> bb 5
14
>>> del aa,bb
PYTHON - NUMBERS

For example,

int float complex


Python supports three different numerical types −
 int (signed integers) 10 0.0 3.14j
 float (floating point real values)
100 15.20 45.j
 complex (complex numbers)
-786 -21.9 9.322e-36j

15
PYTHON - STRINGS

 For example,
 Strings in Python are identified as a
>>> it="Welcome to Python class"
contiguous set of characters represented >>> it
in the quotation marks. 'Welcome to Python class'
 Python allows either pair of single or >>> print(it)
double Welcome to Python class
quotes. >>> print(it[0]) W
>>> print(it[8:10])
 Subsets of strings can be taken using the
to
slice operator ([ ] and [:] )
 Indexes 0 Thebeginnin of the >>> print(it[11:]) Python class
starting at in g >>> print(it[-4:22])
string and their wayfrom to the STTP
working -1 16

end.
PYTHON - STRINGS

 For example,
 The (+) sign is thestring >>> print(it)
plus
concatenation Welcome to Python class
operator.
 The asterisk (*) is the repetition >>> print("Hearty " + it)
operator. Hearty Welcome to Python class
>>> print(it+" By CSE Department")
Welcome to Python class By CSE
Department
>>> print(it*2)
Welcome to Python classWelcome 17
to Python class
PYTHON - LISTS

 Lists are the most versatile of Python's  For example,


compound data types. >>> list1 = [ “Tirunelveli”, 1234 , 15.95, “cse”,
100.5 ]
 List contains items commas >>> list2 = [ “FX”, “cse”,”Department” ]
separated by enclosed within and >>> print(list1)
square brackets ([]). ['Tirunelveli', 1234, 15.95, 'cse', 100.5]
>>> print(list2)
 Lists
One ofarethe
similar to arraysbetween
differences in C. them is that
['FX', 'cse', 'Department']
 all the items belonging to a list can be of >>> print(list1+list2)
different data type. [' 'Tirunelveli ', 1234, 15.95, 'cse', 100.5, 'FX',
'cse', 'Department']
The values stored in a list can be
>>> print(list2*2)
accessed using
['FX', 'cse', 'Department', 'FX', 'cse',
the slice operator ([ ] and [:]) 'Department']
Indexes starting at 0 in the beginning of the >>> print(list1[1:4]) [1234, 15.95, 'cse']
list and working their way to end -1. >>> 18

print(list1[3:])
The plus (+) sign is the list concatenation
['cse', 100.5]
PYTHON - TUPLES

 For example,
 A tuple is another sequence data type that is >>> tuple1 = ( "FX", "cse","Department" )
similar >>> tuple2=("Welcome",1234)
>>> print(tuple1)
to the list.
('FX', 'cse', 'Department')
 A tuple consists of a number of values >>> print(tuple2) ('Welcome', 1234)
separated by commas. >>> print(tuple1+tuple2)
('FX', 'cse', 'Department', 'Welcome', 1234)
 Unlike lists, however, tuples are enclosed >>> print(tuple2*3)
within parenthesis. ('Welcome', 1234, 'Welcome', 1234, 'Welcome',
1234)
 The values stored in a tuple can be accessed >>> print(tuple1[0])
using FX
the slice operator ([ ] and [:]) >>> print(tuple1[1:3]) ('cse', 'Department')

 Indexes starting at 0 in the beginning of the


tuple and working their way to end -1. >>>
19

print(tuple1[1:])
 The plus (+) sign is the concatenation
('cse', 'Department')
PYTHON - TUPLES

 For example,
 The main difference between lists and tuples >>> list2=["Welcome",1234]
are − >>> tuple2=("Welcome",1234)
>>> print(list2)
 Lists are enclosed in brackets ( [ ]
['Welcome', 1234]
) and their elements and size can be >>> print(tuple2) ('Welcome', 1234)
changed,
>>> list2[1]=5000
 Tuples are enclosed in parentheses ( >>> print(list2) ['Welcome', 5000]
( ) ) and >>> tuple2[1]=5000
cannot be updated. Traceback (most recent call last):
File "<stdin>", line 1, in <module>
 Tuples can be thought of as read-only lists.
TypeError: 'tuple' object does not
support item assignment
20
PYTHON - DICTIONARY

• For example,
•>>> dict1={}
 Python's dictionaries are kind of hash-table •>>> dict1['one'] = "ONE"
type. •>>> dict1[2] = "TWO"
•>>> print(dict1)
 A dictionary consist of key-value pairs. •{'one': 'ONE', 2: 'TWO'}
 Dictionaries are enclosed by curly braces ({ •>>> print(dict1['one']) ONE
}) and values can be assigned and accessed •>>> print(dict1[2]) TWO
using square braces ([]). •>>> dict2 = {'name': "class",'code':7, 'dept': "cse"}
•>>> print(dict2)
•{'name': 'class', 'code': 7, 'dept': 'cse'}
•>>> print(dict2.keys()) dict_keys(['name', 'code',
'dept'])

>>> print(dict2.values()) 21

dict_values(['class', 7,
'cse'])
TYPES OF OPERATOR

 Python language supports the following types of


operators −
 Arithmetic Operators
 Comparison (Relational) Operators
 Assignment Operators
 Logical Operators
 Bitwise Operators
 Membership Operators
 Identity Operators 22
PYTHON ARITHMETIC OPERATORS

Operator Description Example (a=10, b=21)


+ Addition Adds values on either side of the operator a + b = 31
- Subtraction Subtracts right hand operand from left hand operand a – b = -11
* Multiplication Multiplies values on either side of the operator a * b = 210
/ Division Divides left hand operand by right hand operand b / a = 2.1
% Modulus Divides left hand operand by right hand operand and returns b%a=1
remainder

** Exponent Performs exponential (power) calculation on operators a**b =10 to the power 21
=
100000000000000000000
0
// Floor Division - The division of operands where the result is 9//2 = 4 and 9.0//2.0 =
the quotient in which the digits after the decimal point are 4.0,
PYTHON COMPARISON OPERATORS

Operator Description Example (a=10, b=21)


== If the values of two operands are equal, then the condition (a == b) is not true = False
becomes true.

!= If values of two operands are not equal, then condition becomes (a!= b) is true = True
true.
> If the value of left operand is greater than the value of right (a > b) is not true =
operand, then condition becomes true. False

< If the value of left operand is less than the value of right (a < b) is true. = True
operand, then condition becomes true.

>= If the value of left operand is greater than or equal to the value (a >= b) is not true = False
of right operand, then condition becomes true.

<= If the value of left operand is less than or equal to the value of (a <= b) is true = True 24

right operand, then condition becomes true.


PYTHON ASSIGNMENT OPERATORS

Operator Description Example (a=10, b=21,c=1)


= Assigns values from right side operands to left side operand c = a + b assigns value of a + b into c

+= Add AND It adds right operand to the left operand and assign the c += a is equivalent to c = c + a
result to left operand

-= Subtract AND It subtracts right operand from the left operand and assign c -= a is equivalent to c = c - a
the result to left operand

*= Multiply AND It multiplies right operand with the left operand and assign c *= a is equivalent to c = c * a
the result to left operand

/= Divide AND It divides left operand with the right operand and assign the c /= a is equivalent to c = c / ac /=
result to left operand a is equivalent to c = c / a

%= Modulus AND It takes modulus using two operands and assign the result to c %= a is equivalent to c = c % a
left operand 25

**= Exponent AND Performs exponential (power) calculation on operators and c **= a is equivalent to c = c ** a
assign
PYTHON BITWISE OPERATORS

Operator Description Example a=60


(00111100), b=13
(00001101)
& Binary AND Operator copies a bit, to the result, if it exists in both operands (a & b) = 12 (means 0000
1100)
| Binary OR It copies a bit, if it exists in either operand. (a | b) = 61 (means 0011 1101)

^ Binary XOR It copies the bit, if it is set in one operand but not both. (a ^ b) = 49 (means 0011 0001)

~ Binary Ones (~a ) = -61 (means 1100 0011)


It is unary and has the effect of 'flipping' bits.
Complement
<< Binary Left Operator shifts the left operand bits towards the left side.The left a << 2 = 240 (means 1111
Shift side bits are removed. Binary number 0 is appended to the end. 0000)

>> Binary Exactly opposite to the left shift operator. The left operand bits are a >> 2 = 15 (means 0000
Right Shift moved towards the right side, the right side bits are removed. Binary 11112)6
number 0 is appended to the beginning.
PYTHON LOGICAL OPERATORS

Operator Description Example a=1 (True), b=0


(False)
and Logical If both the operands are true then condition becomes true. (a and b) is False. (means
AND 0)

or Logical OR If any of the two operands are non-zero (true) then condition (a or b) is True. (means 1)
becomes true.
not Logical Used to reverse the logical state of its operand. ❖ Not (a and b) is True.
NOT (means True)

❖ Not (a or b) is False.
(means False)

27
PYTHON MEMBERSHIP OPERATORS

 Python’s membership operators test for membership in a sequence, such as strings,


lists, or tuples.
 There are two membership operators as explained below −
Operator Description Example
in Evaluates to true if it finds a variable in the specified x in y,
sequence and false otherwise.
here in results in a 1,

if x is a member of sequence y.
not in Evaluates to true if it does not finds a variable in the x not in y,
specified sequence and false otherwise.
here not in results in a 1,

if x is not a member of sequence y.


28
PYTHON IDENTITY OPERATORS

 Identity operators compare the memory locations of two


objects.
 There are two Identity operators as explained below −
Operator Description Example
is Evaluates to true if the variables on either side of the x is y,
operator point to the same object and false here is results in 1, if id(x) equals
otherwise.
id(y).

is not Evaluates to false if the variables on either side of the x is not y,


operator point to the same object and true otherwise.
here is not results in 1,

if id(x) is not equal to id(y).


29
PYTHON OPERATORS PRECEDENCE
 The following table lists all operators from highest precedence to the lowest. Order
- PEMDAS.Operators Meaning

() Parentheses
** Exponent

+x, -x, ~x Unary plus, Unary minus, Bitwise NOT

*, /, //, % Multiplication, Division, Floor division, Modulus

+, - Addition, Subtraction
<<, >> Bitwise shift operators

& Bitwise AND

^ Bitwise XOR

| Bitwise OR

==, !=, >, >=, <, <=, is, is not, in, not in Comparisons, Identity, Membership operators

not Logical NOT


and Logical AND

or Logical OR 30

You might also like