0% found this document useful (0 votes)
5 views29 pages

Operators.pptx

Quick revision notes for computer science

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)
5 views29 pages

Operators.pptx

Quick revision notes for computer science

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/ 29

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 thein interpreter
the command
in
immediate mode. line
 We can directly typein
code, and press Enter to get
Python
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.
4

 For example,
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 and continue for lambda try
other 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
13

>>> xyz
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
bb
14
9
5
>>> 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
 Subsets of strings can be taken using the
>>> print(it[8:10])
slice operator ([ ] and [:] )
 Indexes 0 Thebeginnin of the to
starting at in g >>>
string and their wayfrom to the print(it[11:])
working -1 Python class 16

end. >>> print(it[-4:22])


STTP
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]
 Lists arethe
similar to arraysbetween
in C. them is that >>> print(list2)
One of differences ['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',
 The values stored in a list can be 'cse', 'Department']
accessed using >>> print(list2*2)
['FX', 'cse', 'Department', 'FX', 'cse',
the slice operator ([ ] and [:])
'Department']
 Indexes starting at 0 in the beginning of the >>>
list and working their way to end -1. >>>
print(list1[1:4])
18

print(list1[3:])
 The plus (+) sign is the list concatenation [1234, 15.95, 'cse']
['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)
 Unlike lists, however, tuples are enclosed ('FX', 'cse', 'Department', 'Welcome', 1234)
within parenthesis. >>> print(tuple2*3)
('Welcome', 1234, 'Welcome', 1234, 'Welcome',
 The values stored in a tuple can be accessed 1234)
using >>> print(tuple1[0])
the slice operator ([ ] and [:]) FX
>>>
 Indexes starting at 0 in the beginning of the
print(tuple1[1:3])
tuple and working their way to end -1. >>> 'Department')
('cse',
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)
changed,
('Welcome',
 Tuples are enclosed in parentheses ( 1234)
( ) ) and >>> list2[1]=5000
cannot be updated. >>> print(list2)
 Tuples can be thought of as read-only lists. ['Welcome', 5000]
>>> tuple2[1]=5000
Traceback (most recent call last):
File "<stdin>", line 1, in 20

<module>
PYTHON - DICTIONARY

 For example,
>>> dict1={}
 Python's dictionaries are kind of hash-table >>> dict1['one'] = "ONE"
>>> dict1[2] = "TWO"
type.
>>> print(dict1)
 A dictionary consist of key-value pairs. {'one': 'ONE', 2: 'TWO'}
>>> print(dict1['one'])
 Dictionaries are enclosed by curly braces ({ ONE
}) and values can be assigned and accessed >>> print(dict1[2])
using square braces ([]). TWO
>>> dict2 = {'name': "class",'code':7, 'dept':
"cse"}
>>> print(dict2)
{'name': 'class', 'code': 7, 'dept': 'cse'}
>>> print(dict2.keys())
>>> print(dict2.values()) 21
dict_keys(['name', 'code',
dict_values(['class', 7,
'dept'])
'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 b%a=1
returns 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 9//2 = 4 and 9.0//2.0 =
is the quotient in which the digits after the decimal 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 =
becomes true. False

!= 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 (a >= b) is not true =
value of right operand, then condition becomes true. False

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

of 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 c -= a is equivalent to c = c - a
assign the result to left operand

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

/= Divide AND It divides left operand with the right operand and assign c /= a is equivalent to c = c / ac
the result to left operand /= a is equivalent to c = c
/a
%= Modulus AND It takes modulus using two operands and assign the result c %= a is equivalent to c = c % a
to left operand 25

**= Exponent AND Performs exponential (power) calculation on operators and c **= a is equivalent to c = c ** a
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 a >> 2 = 15 (means 0000
Right Shift are moved towards the right side, the right side bits are removed. 11112)6
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 (a or b) is True. (means 1)
condition 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 x in y,
specified 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 x not in y,
in the 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
otherwise.
1, if id(x) equals

id(y).
is not Evaluates to false if the variables on either side x is not y,
of the 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