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

1 Python Operators

The document provides an overview of operators in Python, defining what an operator is and explaining various types such as arithmetic, assignment, comparison, logical, bitwise, identity, and membership operators. It includes examples of how these operators work with different data types and highlights important concepts like operator precedence, associativity, and the distinction between 'is' and '==' operators. Additionally, it discusses the use of logical operators and the significance of bitwise operations in Python.

Uploaded by

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

1 Python Operators

The document provides an overview of operators in Python, defining what an operator is and explaining various types such as arithmetic, assignment, comparison, logical, bitwise, identity, and membership operators. It includes examples of how these operators work with different data types and highlights important concepts like operator precedence, associativity, and the distinction between 'is' and '==' operators. Additionally, it discusses the use of logical operators and the significance of bitwise operations in Python.

Uploaded by

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

Python-Operators

What is an Operator:
Operator is a symbol that performs certain operations.

The value that the operator operates on is called the operand.

Ex:-

>>> 2+3

Ans:-

Here, + is the operator that performs addition.

2 and 3 are the operands and 5 is the output of the operation.

# The variables below are all integers (whole numbers).

a=1

b=2

c=3

my_sum=a+b

another_sum = 5 + 10

Note:
# In Python we normally use "snake_case" for names. Other languages use
"camelCase".
Types of Operator:
1) Arithmetic Operators

2) Assignment Operators

3) Comparison Operators

4) Logical Operators

5) Bitwise Operators

6) Identity Operators

7) Membership Operators

Arithmetic Operators
Arithmetic operators are used with numeric values to perform common
mathematical operations.
Ex:

[ArithmeticDemo.py]

num1=10

num2=20

print("Num1+Num2=", num1+num2)

print("Num1-Num2=", num1-num2)

print("Num1*Num2=", num1*num2)

print("Num1/Num2=", num1/num2)

print("Num1/Num2=", num2/num1)

print("5^3=",5**3)

print("20%3=",20%3) #2

print("22//7=",22//7) # 3

print("22/7=",22/7) # 3.142857142857143

print("22.0//7=",22.0//7) #3.0
Ex:

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

returns 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.

Note:

We can use +,* operators for str type also.

If we want to use + operator for str type then compulsory both arguments

should be str type only otherwise we will get error.

Ex:

>>> “dd" + 10 # TypeError: must be str, not int

>>> "dd"+"10" # 'dd10’

If we use * operator for str type then compulsory one argument should

be int and other argument should be str type.


>>>2 * "dd"

>>>"dd" * 2

Ex:

2.5*"dd" #TypeError: can't multiply sequence by non-int of type 'float‘

"dd" * "dd” #TypeError: can't multiply sequence by non-int of type 'str‘

+ #String concatenation operator

* #String multiplication operator

Note:

For any number x,

x / 0 and x % 0 always raises "ZeroDivisionError”

Ex:

>>> 10 / 0

>>> 10.0 / 0

>>> 10 % 0

More ex on Arithmetic Operator:

a = 15 b = 4

c = a+b # output : 19

c = a*b # output : 60

c =a-b. #output : 11

c=a**b

=> Now the question is what is **

=> It is said as power


c= a**b (15 )^4 = 50,625

++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

Division ( / )
It’s result in float
Ex:
a = 15 b = 4

c = a/b # 3.5

Floor Division (//)

++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

Assignment Operator
The equal sign (=) is used to assign a value to a variable. After wards, no result is
displayed before the next interactive Prompt

>>> width=20

>>> height = 5 * 9

>>> width * height

Ans: 900
Expressions
The instruction that we write using operators is called expressions .

Ex:

c=a+b
# c , a , b are operands.
# = , + are operators.
Lets take example:
d = 2+3*5 #3*5=15
d = 2+15
d=17
=> This happened because of precedence
=> First multiplication takes place because it has
higher precedence than addition
=>They will execute based on their precedence
d = 2*3 + 8/2
= 6 + 4.0 = 10.0
=> When priority is same in that case associativity comes in the picture.

=> Associativity either LR or RL.

To increase the precedence we use ( )


2+3*5 # first multiplication take place because it have higher precedence

than addition

2+15 = 17
By using parentheses (2+3) * 5

# here addition will take place because parentheses have higher

precedence than all

5 * 5 = 25

What if we are having


Compound Assignment Operator
We can combine assignment operator with some other operator to form

Compound assignment operator.

Ex:

x=5 # This is Assignment

x=x+10

or

x+=10 # x=x+10

Ex:

[AssignopDemo.py]

#Assignment operators

num1=10

num2=20

num3=num1+num2
print("num3=",num3)

num3+=num2 #num3=num3+num2

print(num3)

Ex:

maths_operators = 1 + 3 * 4 / 2 - 2

print(maths_operators)

Ans:- ?

5.0

# A float is a "floating point number"; one with a decimal point.

# Normally division results in a floating point number.

Ex:-

float_division = 12 / 3

print(float_division)

Ans:- 4.0

Ex:

integer_division = 12 // 3 # drops anything after the decimal (no rounding!)

print(integer_division)

division_with_reminder = 12 // 5 # should be 2.4

print(division_with_reminder) # prints 2
Ex:

rem = 12%5

print(rem) #prints 2

# For every even number, the remainder when divided by 2 is always 0.

# For every odd number, the remainder when divided by 2 is always 1.

# We can check whether a number is odd or even just by checking the reminder!

x=37

rem = x % 2

print(rem) # should print 1, therefore it is odd


Ans:

We're creating some variables but we never print anything out, so the user

sees nothing.

Comparison Operator / Relational Operator


Operators that compare values and return true or false.

A boolean is a true/false, yes/no, one/zero value. We can use it to make

decisions.In Python, True and False are keywords to represent these

Values.

Ex:

truthy = True

falsy = False
Note:

Comparison operator always return the Boolean Value (True/False)

Ex:
Ex:

age = 20
is_over_age = age >= 18 #True
is_under_age = age < 18 #False
is_twenty = age == 20 #True
print(is_over_age)
print(is_under_age)
print(is_twenty)
Ex:

[CompareDemo.py]
#Comparison operators

num1=10

num2=20

num3=num1+num2

print("Is num3 > num2 ?",num3>num2) # True

print("Is num3 == num2 ?",num3==num2) # False

print("Is num1 != num2 ?",num1!=num2) # True

++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
We can apply relational operators for str types also

Ex-2:

a=“DD"

b=“DD"

print("a > b is ", a>b) #False

print("a >= b is ", a>=b) #True

print("a < b is ",a<b) #False

print("a <= b is ",a<=b) #True

Ex:

print(True>True) #False

print(True>=True) #True

print(10>True) #True

print(False>True) #False

print(10 > 'dd') # TypeError: '>' not supported between

instances of 'int' and 'str'

Note:
Chaining of relational operators is possible. In the chaining, if all comparisons
returns True then only result is True.

If at least one comparison returns False then the result is False.


Ex:

10<20 #True

10<20<30 #True

10<20<30<40 #True

10<20<30<40>50 #False

Equality operators
== , !=

We can apply these operators for any type of data even for incompatible types
also

Ex:

>>>10==20 #False

>>> 10!= 20 #True

>>> 10==True #False

>>> False==False #True

>>> "dd"=="dd“ #True

>>> 10=="dd” #False

Note:
input() is the predefined function with the help of it we can accept any thing

but it always return as string.


Ex:

We ask the user for a number, and check that it matches our 'secret number'.

my_number=5

user_number = int(input("Enter a number: "))

print(my_number == user_number)

print(my_number != user_number)

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.

Ex:

>>>10==20==30==40 #False

>>> 10==10==10==10 #True


Logical Operator
Logical operators are used on conditional statements (either True or

False). They perform Logical AND, Logical OR and Logical NOT operations.

EX:

Logical and:
`and` is used to get two Booleans and check whether they are both True.

If either or both are not True, then the resultant expression is also False.

Ex:

var1 = True and True

var2 = True and False

print(var1) #True

print(var2) #False
Logical Or:
`or` is used to get the second value if the first one is False. If the first one

is True, it gets the first one.

Ex:

which_one_is_it = True or False

second_one = False or True

first_one = True or True

neither = False or False

Logical Not:
`not` is used to invert the Boolean. Gets the opposite value!

absolutely = not False

another_no = not True

# These(Boolean Value) can be used with variables as well, of course!

is_programmer = True

is_learning = False

awesome = is_programmer and is_learning #False

less_awesome = is_programmer and not is_learning # True

Note:

If We are Using More than one Logical Operator at a time

In that case priority of Logical Operator is Not/and/OR


Ex:

is_programmer = True

is_learning = False

is_designer = False

great_guy = (is_programmer or is_designer) and is_learning

print(great_guy) #False

Ex:

is_programmer = True

is_learning = False

is_designer = False

great_guy = is_programmer or is_designer and is_learning

print(great_guy) #True

Bitwise Logical Operators


Bitwise operators are used to perform bitwise calculations on integers.

The integers are first converted into binary and then operations are

Performed on bit by bit, hence the name bitwise operators.

Then the result is returned in decimal format.

These operators are applicable only for int and boolean types.
Note:

If these operator operates on boolean operand in that case these operators are
known as logical operator. where as if these operator works on numeric value in
that case these are known as bitwise operator.

By mistake if we are trying to apply for any other type then we will get Error.

Ex Of Bitwise Operator:

&,|,^,~,<<,>>

Ex:
print(4 & 5) # valid

print(10.5 & 5.6) # Type Error: unsupported operand

type(s) for &: 'float' and 'float‘

print(True & True) #valid

& # 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

<< #bitwise Left shift

>> #Bitwise Right Shift


Ex:

# This demo is for Bitwise Operator

x=6

y=2

print("BitWise And =",x & y) # 2

print("BitWise Or =",x | y) # 6

print("BitWise Xor =",x ^ y) # 4


bitwise complement operator(~):
We have to apply complement for total bits.

Ex:

print(~5) #-6

Note:
The most significant bit acts as sign bit.

0 value represents +ve number where as 1 represents -ve value.

Note:
Positive numbers will be represented directly in the memory

where as -ve numbers will be represented indirectly in 2's complement form.

Left Shift Operator


Right Shift Operator

Ex:

#This demo is for Shift Operator

print("Right Shift =",15>>2)

print("Left Shift =",15<<2)

Note:

In The Case of Left Shift Operator We Do Multiplication

Where as in the Case of Right Shift Operator We Do the Division.

++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Identity operators
Identity operator is used to determine whether a value is of a certain class or type.

They are usually used to determine the type of data a certain variable contains.

There are different identity operators such as

1) ‘is’ operator:
Evaluates to true if the variables on either side of the operator point to the same

object and false otherwise.

Ex:

x=5

if (type(x) is int):

print("true")

else:

print("false")

2) ‘is not’ operator


Evaluates to false if the variables on either side of the operator point to the

same object and true otherwise.

Ex:

# use of 'is not' identity operator

x = 5.2

if (type(x) is not int):

print("true")

else:

print("false")
Note:
Identity operators are used to compare the objects, not if they are equal, but if

They are actually the same object, with the same memory location

X1 = 'Welcome!'

X2 = 1234

Y1 = 'Welcome!'

Y2 = 1234

print(X1 is Y1) #True

print(X1 is not Y1) #False

print(X1 is not Y2) #True

print(X1 is X2) #False


Que)
What is the difference b/w is operator and == operator ?
Ans)
We can use is operator for address comparison whereas == operator for content

comparison.

Ans:-

== operator compare the value whereas is operator Compares addresses.

Ex:

x = ["DD", "Dev"]

y = ["DD", "Dev"]

z=x

print(x is z) # returns True because z is the same object as x

print(x is y) # returns False because x is not the same object as y, even if they have the

same content

print(x == y) # to demonstrate the difference between "is" and "=="

# this comparison returns True because x is equal to y

is not:
Returns true if both variables are not the same object x is not y.

x = ["DD", "Dev"]

y = ["DD", "Dev"]

z=x

print(x is not z)# returns False because z is the same object as x

print(x is not y) # returns True because x is not the same object as y, even if they

have the same content


print(x != y) # to demonstrate the difference betweeen "is not" and "!=": this

comparison returns False because x is equal to y.

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]

in:
Returns True if the given object present in the specified Collection.

not in:
Returns True if the given object not present in the Specified
Collection.

Ex:

list1=[“DD",”Dev",“Shweta",“Lata"]

print(“Dev" in list1) #True

print(”Harsh" in list1) #False

print(“Harsh" not in list1) #True

Ex:

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
Operator Precedence
If multiple operators present then which operator will be evaluated first is decided
by operator precedence.

Ex:

print(3+10*2) #23

print((3+10)*2) #26

The following list describes operator precedence in Python

() => Parenthesis

** => Exponential operator

~,- => Bitwise complement operator,unary minus operator

*,/,%,// => multiplication,division,modulo,floor division

+,- => addition,subtraction

<<,>> => Left and Right Shift

& => bitwise And

^ => Bitwise X-OR

| => Bitwise OR

>,>=,<,<=, ==, != = =>Relational or Comparison operators

=,+=,-=,*=... = =>Assignment operators

is , is not => Identity Operators

in , not in => Membership operators

not => Logical not

and => Logical and

or => Logical or
Ex:

a=30

b=20

c=10

d=5

print((a+b)*c/d) #100.0

print((a+b)*(c/d)) #100.0

print(a+(b*c)/d) #70.0

3/2*4+3+(10/5)**3-2

3/2*4+3+2.0**3-2

3/2*4+3+8.0-2

1.5*4+3+8.0-2

6.0+3+8.0-2 #15.0

++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

Output using print() function


The simplest way to produce output is using the print()
function where you can pass zero or more
values/expressions separated by commas.
This function converts the expressions you pass into a
string before writing to the screen.

Syntax:
print(value(s),sep= ‘ ‘ , end=‘\n’,file=file,flush=flush)
Parameters:

value(s): Any value , and as many as you like. Will be


converted to string before printed.

sep=’separator’: (Optional) Specify how to separate the


objects, if there is more than one. Default : ’ ‘

end=’end’: (Optional) Specify what to print at the end.

Default : ‘\n’

file: (Optional) An object with a write method.

Default :sys.stdout

flush: (Optional) A Boolean, specifying if the output is


flushed

(True) or buffered (False). Default: False

Returns: It returns output to the screen.

Though it is not necessary to pass arguments in the print() function, it


requires an empty parenthesis at the end that tells python to execute the
function rather calling it by name.
Now, let’s explore the optional arguments that can be used with the print()
function.
1. String Literals:
String literals in python’s print statement are primarily used to format or
design how a specific string appears when printed using the print() function.

 \n : This string literal is used to add a new blank line while printing a
statement.
 “” : An empty quote (“”) is used to print an empty line.

Ex:
print("Career Compiler \n is best for DSA Content.")

2. end= ” ” statement
The end keyword is used to specify the content that is to be printed at the
end of the execution of the print() function. By default, it is set to “\n”, which
leads to the change of line after the execution of print() statement.
Example:

# This line will automatically add a new line before


the next print statement

print ("CareerCompiler is the best platform for DSA


content")

# This print() function ends with "**" as set in the


end argumennt.
print ("CareerCompiler is the best platform for DSA
content", end= "**")

3. flush Argument
In Python, you can flush the output of the print() function by using the flush parameter. The flush
parameter allows you to control whether the output should be immediately flushed or buffered.

By default, the print() function buffers the output, meaning that it may not be immediately displayed on
the screen or written to a file. However, you can force the output to be flushed immediately by setting
the flush parameter to True.

Note:

Please Execute the below program in command prompt by python command

Ex:
import time

for i in range(5,0,-1):

print(i,end=">>>",flush=True)

#print(i,end=">>>",flush=False) #Default Behaviour

time.sleep(1)

print("Over and Out")

4. Separator
The print() function can accept any number of positional arguments.
These arguments can be separated from each other using a “,” separator.
These are primarily used for formatting multiple statements in a single print()
function.

b = "for"

print("DD", b , "DSA")

5. file Argument
Contrary to popular belief, the print() function doesn’t convert the messages
into text on the screen.

These are done by lower-level layers of code, that can read data(message)
in bytes. The print() function is an interface over these layers, that delegates
the actual printing to a stream or file-like object.
By default, the print() function is bound to sys.stdout through
the file argument.

print() function in Python3 supports a ‘file‘ argument, which specifies where


the function should write a given object(s) to. If not specified explicitly, it
is sys.stdout by default.
It serves two essential purposes:
Print to STDERR
Print to external file
Note :
The ‘file’ parameter is found only in Python 3.x or later.

Printing to STDERR :
Specify the file parameter as sys.stderr instead of the default value. This is
very useful when debugging a small program (It would be better to use a
debugger in other cases).

Ex:
# Code for printing to STDERR

import sys

print('DD Singh', file = sys.stderr)

print('DD Singh', file = sys.stdout)

Printing to a specific file:


Instead of the default value, specify the file parameter with the name of the
required file. If the file does not exist, a new file by that name is created and
written to.
Ex:
# Code for printing to a file

sample=open('e:/UPL.txt', 'w')

print('DD Singh', file = sample)

sample.close()

Ex:

x=10

print(x)
x=10

y=20

print(x,y)

print(x, “,”,y)

print(x,y,sep=”,”)

print(x,y,sep=”:”)

print(“AB”+”CD”)

+++++++++++++++++++++++++++++++++++++++
+

Practice Ex:
+++++++++++++++++++++++++++++++++++++++
++++++

Replacement Operator {} / format()


function:
str.format() is one of the string formatting methods in Python3,
which allows multiple substitutions and value formatting.

This method lets us concatenate elements within a string through


positional formatting.

Using a Single Formatter:

Formatters work by putting in one or more replacement fields and


placeholders defined by a pair of curly braces {} into a string and
calling the str.format().

The value we wish to put into the placeholders and concatenate


with the string passed as parameters into the format function.

Syntax:-

{} .format (value):-

Parameters :-

(value):-
Can be an integer, floating point numeric constant, string,
characters

Or even variables.

Return type:-

Returns a formatted string with the value passed as


parameter in the

Placeholder position.

# using format option in a simple string:-

print ("{}, Is a portal for IT Students.".format("CareerCompiler"))

# using format option for a value stored in a variable:-

str="Hi My Name is {}"

print(str.format("DD Singh"))

#formatting a string using a numeric constant:-

print("Hello, I am {} years old !".format(40))

Using Multiple Formatters:

Multiple pairs of curly braces can be used while formatting the


string. Let’s say if another variable substitution is needed in
sentence, can be done by adding a second pair of curly braces
and passing a second value into the method. Python will replace
the placeholders by values in order.

Syntax:

{} {} .format (value1, value2)

Parameters:
(value1, value2):- Can be integers, floating point numeric
constants, strings, characters and even variables. Only difference
is, the number of values passed as parameters in format()
method must be equal to the number of placeholders created in
the string.

Errors and Exceptions

IndexError: Occurs when string has an extra placeholder and we


didn’t pass any value for it in the format() method. Python usually
assigns the placeholders with default index in order like 0, 1, 2,
3…. to access the values passed as parameters. So when it
encounters a placeholder whose index doesn’t have any value
passed inside as parameter, it throws IndexError.

# Python program demonstrating Index error


my_string="{}, is a {} {} science portal for {}"

print(my_string.format("CareerCompiler", "computer", "Students"))

Right Way is

my_string = "{}, is a {} science portal for {}"

print(my_string.format("CareerCompiler", "computer",
"Students"))

# different data types can be used in formatting


print ("Hi ! My name is {} and I am {} years old".format("DD", 40))
#The values passed as parameters are replaced in order
of

their entry

print ("This is {} {} {} {}".format("one", "two", "three", "four"))

Formatters with Positional and Keyword Arguments:-

When placeholders {} are empty, Python will replace the values


passed through str.format () in order.

The values that exist within the str.format() method are


essentially tuple data types and each individual value contained
in the tuple can be called by its index number, which starts with
the index number 0. These index numbers can be passes into the
curly braces that serve as the placeholders in the original string.

Syntax :-

{0} {1}.format(positional_argument, keyword_argument)

Parameters: (positional_argument, keyword_argument)

Positional_argument can be integers, floating point numeric


constants, strings, characters and even variables.

Keyword_argument is essentially a variable storing some value,


which is passed as parameter.

# To demonstrate the use of formatters


# with positional key arguments.

# Positional arguments are placed in order

print("{0} love {1}!!".format("CCTeam","Students"))

# Reverse the index numbers with the parameters of the


placeholders

print("{1} love {0}!!".format("CCTeam", "Students"))

print("Every {} should know the use of {} {} programming"

.format("programmer", "Open", "Source"))

# Use the index numbers of the values to change the order that

# they appear in the string

print("Every {3} should know the use of {1} {2} programming


and {0}"

.format("programmer", "Open", "Source", "Operating


Systems"))

# Keyword arguments are called by their keyword name

print("{CCTeam} is a {0} science portal for {1}"

.format("computer", "Students", CCTeam="CareerCompiler")


+++++++++++++++++++++++++++++++++++++++
++++++

Command Line Arguments


Python supports the creation of programs that can be run on the
command line / Command Prompt.
The arguments that are given after the name of the
program

in the command line shell of the operating system are


known

as Command Line Arguments.

Using sys.argv:

argv is not Array, it is a List. It is available in sys Module.

The Argument which are passing at the time of execution

are called Command Line Arguments.

The Python sys module provides access to any of the

Command-line arguments via sys.argv. It solves two

purposes

1) sys.argv is the list of command-line arguments

2) len(sys.argv) is the number of command-line arguments

that you have in your command line.

sys.argv[0] is the program, i.e. script name

len(sys.argv) Provides the number of command line

Arguments.
Executing Python:-
You can execute Python in this way:

Ex:

To check type of argv from sys

import sys

print(type(sys.argv))

E:\Python_classes\py test.py

#Write a Program to display Command Line Arguments

[CommandDemo.py]

from sys import argv


print(“The Number of Command Line Arguments:”, len(argv))

print(“The List of Command Line Arguments:”, argv)

print(“Command Line Arguments one by one:”)

for x in argv:
print(x)

E:\Demos>py CommandDemo.py 10 20 30

Ex:- [Sum.py]

from sys import *

sum=0

args=argv[1:]

for x in args :

n=int(x)

sum=sum+n

print("The Sum:",sum)

E:\Demos>py Sum.py 10 20 30 40

Note1:

usually space is separator between command line


arguments.

If our command line argument itself contains space


then we

should enclose within double quotes (but not single


quotes)

Ex:-

from sys import argv


print(argv[1])

E:\Demos>py test.py DD Singh #DD

E:\Demos>py test.py ‘DD Singh‘ #‘DD

E:\Demos>py test.py “DD Singh“ #DD Singh

Note2:-

Within the Python program command line arguments


are

Available in the String form. Based on our requirement,


we can

Convert into corresponding type by using type casting


methods.

Ex:-

from sys import argv

print(argv[1]+argv[2])

print(int(argv[1])+int(argv[2]))

E:\Demos>py test.py 10 20

Note3:-

If we are trying to access command line arguments with

out of range index then we will get Error.

Ex:-
from sys import argv

print(argv[100])

E:\Demos>py test.py 10 20

You might also like