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

Unit 2 Python

The document provides an introduction to operators in Python, detailing various types including arithmetic, comparison, assignment, bitwise, and logical operators. Each type is explained with definitions and examples, showcasing their syntax and functionality. Code snippets demonstrate the use of these operators, along with their expected outputs.

Uploaded by

Anshika Gupta
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 views8 pages

Unit 2 Python

The document provides an introduction to operators in Python, detailing various types including arithmetic, comparison, assignment, bitwise, and logical operators. Each type is explained with definitions and examples, showcasing their syntax and functionality. Code snippets demonstrate the use of these operators, along with their expected outputs.

Uploaded by

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

Created with a trial version of Syncfusion PDF library or registered the wrong key

in your application. Click here to obtain the valid key.


PYTHON (Unit – II) Operators by Akif Sir
An Introduction to Operators in Python
In general, Operators are the symbols used to perform a specific operation on different values and variables. These values and variables
are considered as the Operands, on which the operator is applied. Operators serve as the foundation upon which logic is constructed in a
program in a particular programming language. In every programming language, some operators perform several tasks.

Different Types of Operators in Python

Same as other languages, Python also has some operators, and these are given below -

1. Arithmetic Operators
2. Comparison Operators
3. Assignment Operators
4. Logical Operators
5. Bitwise Operators
6. Membership Operators
7. Identity Operators

Let us now discuss these operators used in Python in the following sections.

1. Arithmetic Operators ry.


ra
lib
Python Arithmetic Operators are used on two operands to perform basic mathematical operators F like addition, subtraction, multiplication,
and division. There are different types of arithmetic operators available in Python including PD the '+' operator for addition, '-' operator for
n '//' for floor division.
subtraction, '*' for multiplication, '/' for division, '%' for modulus, '**' for exponent and
o
u si
f
nc
Let us consider the following table of arithmetic operators for a detailed explanation.
S y
S. No. Operator Syntax Description of
1 + (Addition) r=a+b This operatorn is used to add two operands. For example, if a = 15, b = 10 => a + b
= 15 + 10si=o25
r is used to subtract the second operand from the first operand. If the
ve is less than the second operand, the value results negative. For
2 - (Subtraction) r=a-b This operator
firstl operand
ria
texample, if a = 20, b = 5 => a - b = 20 – 5 = 15
3 / (divide) r=a/b a This operator returns the quotient after dividing the first operand by the second
ith operand. For example, if a = 15, b = 4 => a / b = 15 / 4 = 3.75
4 * (Multiplication) r=a*b d w This operator is used to multiply one operand with the other. For example, if a =
t e 20, b = 4 => a * b = 20 * 4 = 80
5 % (reminder) ab
r = ae% This operator returns the reminder after dividing the first operand by the second
r
C operand. For example, if a = 20, b = 10 => a % b = 20 % 10 = 0
6 ** (Exponent) r = a ** b As this operator calculates the first operand's power to the second operand, it is an
exponent operator. For example, if a = 2, b = 3 => a**b = 2**3 = 2^3 = 2*2*2 =
8
7 // (Floor division) r = a // b This operator provides the quotient's floor value, which is obtained by dividing
the two operands. For example, if a = 15, b = 4 => a // b = 15 // 4 = 3

Program Code:

Now we give code examples of arithmetic operators in Python. The code is given below -

a = 46 # Initializing the value of a


b = 4 # Initializing the value of b
print("For a =", a, "and b =", b,"\nCalculate the following:")
# printing different results
print('1. Addition of two numbers: a + b =', a + b)
print('2. Subtraction of two numbers: a - b =', a - b)
print('3. Multiplication of two numbers: a * b =', a * b)
print('4. Division of two numbers: a / b =', a / b)
print('5. Floor division of two numbers: a // b =',a // b)
print('6. Reminder of two numbers: a mod b =', a % b)
print('7. Exponent of two numbers: a ^ b =',a ** b)
Output:
Now we compile the above code in Python, and after successful compilation, we run it. Then the output is given below -

For a = 46 and b = 4
Calculate the following:
1. Addition of two numbers: a + b = 50
2. Subtraction of two numbers: a - b = 42
3. Multiplication of two numbers: a * b = 184
4. Division of two numbers: a / b = 11.5
5. Floor division of two numbers: a // b = 11
6. Reminder of two numbers: a mod b = 2
7. Exponent of two numbers: a ^ b = 4477456

2. Comparison Operators
Python Comparison operators are mainly used for the purpose of comparing two values or variables (operands) and return a Boolean value
as either True or False accordingly. There are various types of comparison operators available in Python including the '==', '!=', '<=', '>=',
'<', and '>'.

Let us consider the following table of comparison operators for a detailed explanation.

S. No. Operator Syntax Description


1 == a == b Equal to: If the value of two operands is equal, then the condition becomes true.
2 != a != b Not Equal to: If the value of two operands is not equal, then the condition becomes true.
3 <= a <= b
y. than or equal to the second
Less than or Equal to: The condition is met if the first operand is smaller
operand. r
4 >= a >= b Greater than or Equal to: The condition is met if the first operandbisragreater than or equal to the second
operand. l i
5 > a>b Greater than: If the first operand is greater than the second D
F
operand, then the condition becomes true.
6 < a<b P
Less than: If the first operand is less than the second operand, then the condition becomes true.
ion
us
Program Code:

n cf
Sy
Now we give code examples of Comparison operators in Python. The code is given below -
o f
a = 46 # Initializing the value of a
o n
b = 4 # Initializing the value of b i
print("For a =", a, "and b =", b,"\nCheck the following:") e rs
v
al
# printing different results
print('1. Two numbers are equal or not:', a ==rb) i
ta != b)
print('2. Two numbers are not equal or not:', a
itah >=
print('3. a is less than or equal to b:', a <= b)
w
print('4. a is greater than or equal to b:', b)
print('5. a is greater b:', a > b) d
print('6. a is less than b:', a < b) te
a
Output: re
C
Now we compile the above code in Python, and after successful compilation, we run it. Then the output is given below -

For a = 46 and b = 4
Check the following:
1. Two numbers are equal or not: False
2. Two numbers are not equal or not: True
3. a is less than or equal to b: False
4. a is greater than or equal to b: True
5. a is greater b: True
6. a is less than b: False

3. Assignment Operators
Using the assignment operators, the right expression's value is assigned to the left operand. Python offers different assignment operators
to assign values to the variable. These assignment operators include '=', '+=', '-=', '*=', '/=', '%=', '//=', '**=', '&=', '|=', '^=', '>>=', and '<<='.

Let us consider the following table of some commonly used assignment operators for a detailed explanation.

S. No. Operator Syntax Description


1 = a=b+c This operator assigns the value of the right expression to the left operand.
2 += a += b => a = a + b Add AND: This operator adds the operand on the right side to the operand on the left
side and assigns the resultant value to the left operand. For example, if a = 15, b = 20
=> a += b will be equal to a = a + b and therefore, a = 15 + 20 => a = 35
3 -= a -= b => a = a - b Subtract AND: This operator subtracts the operand on the right side from the operand
on the left side and assigns the resultant value to the left operand. For example, if a =
47, b = 32 => a -= b will be equal to a = a - b and therefore, a = 47 - 32 => a = 15
4 *= a *= b => a = a * b Multiply AND: This operator multiplies the operand on the right side with the
operand on the left side and assigns the resultant value to the left operand. For
example, if a = 12, b = 4 => a *= b will be equal to a = a * b and therefore, a = 12 * 4
=> a = 48
5 /= a /= b => a = a / b Divide AND: This operator divides the operand on the left side with the operand on
the right side and assign the resultant value to the left operand. For example, if a = 15,
b = 2 => a /= b will be equal to a = a / b and therefore, a = 15 / 2 => a = 7.5
6 %= a %= b => a = a % b Modulus AND: This operator calculates the modulus of using the left-side and right-
side operands and assigns the resultant value to the left operand. For example, if a =
20, b = 10 => a %= b will be equal to a = a % b and therefore, a = 20 % 10 => a = 0
7 **= a **= b => a = a ** b Exponent AND: This operator calculates the exponent value using the operands on
both side and assign the resultant value to the left operand. For example, if a = 2, b =
3 => a **= b will be equal to a = a ** b and therefore, a = 2 ** 3 = 8
8 //= a //= b => a = a // b Divide (floor) AND: This operator divides the operand on the left side with the
operand on the right side and assign the resultant floor value to the left operand. For
example, if a = 15, b = 2 => a //= b will be equal to a = a // b and therefore, a = 15 // 2
=> a = 7
Program Code:

Now we give code examples of Assignment operators in Python. The code is given below -
ry.
ra
a = 34 # Initialize the value of a lib
b=6 # Initialize the value of b F
# printing the different results
PD
on
print('a += b:', a + b)
print('a -= b:', a - b) i
us
cf
print('a *= b:', a * b)
print('a /= b:', a / b)
print('a %= b:', a % b) y n
print('a **= b:', a ** b)
ofS
print('a //= b:', a // b) n
Output:
sio
r
ve
al compilation, we run it. Then the output is given below -
Now we compile the above code in Python, and after successful
tri
a += b: 40 a
a -= b: 28 ith
a *= b: 204 w
a /= b: 5.666666666666667 ed
a %= b: 4
eat
a **= b: 1544804416 r
a //= b: 5 C

4. Bitwise Operators
The two operands' values are processed bit by bit by the bitwise operators. There are various Bitwise operators used in Python, such as
bitwise OR (|), bitwise AND (&), bitwise XOR (^), negation (~), Left shift (<<), and Right shift (>>). Consider the case below.

For example,

if a = 7
b=6
then, binary (a) = 0111
binary (b) = 0110

hence, a & b = 0011


a | b = 0111
a ^ b = 0100
~ a = 1000
Let, Binary of x = 0101
Binary of y = 1000
Bitwise OR = 1101
8421
1 1 0 1 = 8 + 4 + 1 = 13
Bitwise AND = 0000
0000 = 0

Bitwise XOR = 1101


8421
1 1 0 1 = 8 + 4 + 1 = 13
Negation of x = ~x = (-x) - 1 = (-5) - 1 = -6
~x = -6
Let us consider the following table of bitwise operators for a detailed explanation.

S. No. Operator Syntax Description


1 & a&b Bitwise AND: 1 is copied to the result if both bits in two operands at the same location are 1. If
not, 0 is copied.
2 | a|b Bitwise OR: The resulting bit will be 0 if both the bits are zero; otherwise, the resulting bit will be
1.
3 ^ a^b Bitwise XOR: If the two bits are different, the outcome bit will be 1, else it will be 0.

4 ~ ~a Bitwise NOT: The operand's bits are calculated as their negations, so if one bit is 0, the next bit
will be 1, and vice versa.
5 << a << Bitwise Left Shift: The number of bits in the right operand is multiplied by the leftward shift of
the value of the left operand.
6 >> a >> Bitwise Right Shift: The left operand is moved right by the number of bits present in the right
operand.
Program Code:

ry.
Now we give code examples of Bitwise operators in Python. The code is given below -
ra
lib
a=7 # initializing the value of a F
b=8 # initializing the value of b PD
# printing different results
ion
us
print('a & b :', a & b)
print('a | b :', a | b)
print('a ^ b :', a ^ b) n cf
y
fS
print('~a :', ~a)
print('a << b :', a << b) o
print('a >> b :', a >> b) n
Output: sio
r
l ve
ia compilation, we run it. Then the output is given below -
Now we compile the above code in Python, and after successful
tr
a
ith
a&b:0
a | b : 15
w
a ^ b : 15
ed
at
~a : -8
a << b : 1792
r e
a >> b : 0 C
5. Logical Operators
The assessment of expressions to make decisions typically uses logical operators. Python offers different types of logical operators such
as and, or, and not. In the case of the logical AND, if the first one is 0, it does not depend upon the second one. In the case of the logical
OR, if the first one is 1, it does not depend on the second one.

Let us consider the following table of the logical operators used in Python for a detailed explanation.

S. No. Operator Syntax Description


1 and a and b Logical AND: The condition will also be true if the expression is true. If the two expressions
a and b are the same, then a and b both must be true.
2 or a or b Logical OR: The condition will be true if one of the phrases is true. If a and b are the two
expressions, then either a or b must be true to make the condition true.
3 not not a Logical NOT: If an expression a is true, then not (a) will be false and vice versa.

Program Code:

Now we give code examples of Logical operators in Python. The code is given below -

a=7 # initializing the value of a


# printing different results
print("For a = 7, checking whether the following conditions are True or False:")
print('\"a > 5 and a < 7\" =>', a > 5 and a < 7)
print('\"a > 5 or a < 7\" =>', a > 5 or a < 7)
print('\"not (a > 5 and a < 7)\" =>', not(a > 5 and a < 7))
Output:

Now we compile the above code in Python, and after successful compilation, we run it. Then the output is given below -

For a = 7, checking whether the following conditions are True or False:


"a > 5 and a < 7" => False
"a > 5 or a < 7" => True
"not (a > 5 and a < 7)" => True

6. Membership Operators
We can verify the membership of a value inside a Python data structure using the Python membership operators. The result is said to be
true if the value or variable is in the sequence (list, tuple, or dictionary); otherwise, it returns false.

S. No. Operator Description

1 in If the first operand (value or variable) is present in the second operand (sequence), it is evaluated to be true.
Sequence can either be a list, tuple, or dictionary

2 not in
y. (sequence), the evaluation is true.
If the first operand (value or variable) is not present in the second operand
Sequence can either be a list, tuple, or dictionary ar r
lib
Program Code: F
PD
Now we give code examples of Membership operators in Python. The code is giveniobelow -
n
us
# initializing a list n cf
y
fS
myList = [12, 22, 28, 35, 42, 49, 54, 65, 92, 103, 245, 874]
o
# initializing x and y with some values n
x = 31 sio
y = 28 e r
v
al
# printing the given list
tri
print("Given List:", myList) a
i t h
# checking if x is present in the list orwnot
if (x not in myList):
t eindthe given list.")
print("x =", x,"is NOT presenta
else: re
print("x =", x,"is presentCin the given list.")

# checking if y is present in the list or not


if (y in myList):
print("y =", y,"is present in the given list.")
else:
print("y =", y,"is NOT present in the given list.")
Output:

Now we compile the above code in Python, and after successful compilation, we run it. Then the output is given below -

Given List: [12, 22, 28, 35, 42, 49, 54, 65, 92, 103, 245, 874]
x = 31 is NOT present in the given list.
y = 28 is present in the given list.

7. Identity Operators
Python offers two identity operators as is and is not, that 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.

S. No. Operator Description


1 is If the references on both sides point to the same object, it is determined to be true.
2 is not If the references on both sides do not point at the same object, it is determined to be true.
Program Code:

Now we give code examples of Identity operators in Python. The code is given below -

# initializing two variables a and b


a = ["Rose", "Lotus"]
b = ["Rose", "Lotus"]
# initializing a variable c and storing the value of a in c
c=a
# printing the different results
print("a is c => ", a is c)
print("a is not c => ", a is not c)
print("a is b => ", a is b)
print("a is not b => ", a is not b)
print("a == b => ", a == b)
print("a != b => ", a != b)
Output:

Now we compile the above code in python, and after successful compilation, we run it. Then the output is given below -

a is c => True
a is not c => False
a is b => False
a is not b => True
ry.
ra
a == b => True

lib
a != b => False
F
8. Operator Precedence PD
n
s io
The order in which the operators are examined is crucial to understand since it tells
is a list of the Python operators' precedence tables. cfu us which operator needs to be considered first. Below
Syn
S. No. perator Description of
1 ** Overall other operators employed n
sio in the expression, the exponent operator is given precedence.
2 ~, +, - r
the minus, unary plus, andenegation.
v
al the modules, the division, and the multiplication.
tri
3 *, /, %, // the division of the floor,
4 +, - Binary plus, and minus
5 >>, << a
Left shift. and right
i th shift
6 & Binary and.w
7 ^, | ed and or
Binary txor,
a
8 <=, <, >, >=
re operators.
Comparison operators (less than, less than equal to, greater than, greater then equal to).
9 <>, ==, != C
Equality
10 =, %=, /=, //=, -=, +=, Assignment operators
*=, **=
11 is, is not Identity operators
12 in, not in Membership operators
13 not, or, and Logical operators

1. Output Statements in Python


Python provides the print() function to display output.

Syntax:
print(value, ..., sep=' ', end='\n', file=[Link], flush=False)

 value: The data to be displayed.


 sep: Separator between multiple values (default is space ' ').
 end: Defines what comes at the end of the output (default is a newline '\n').
 file: Where the output should go (default is [Link]).
 flush: Whether to force the output to be written immediately.

Examples:
1. # Simple output
2. print("Hello, World!")
3. # Printing multiple values with a separator
4. print("Python", "Programming", sep="-")
5. # Changing the end character
6. print("Hello", end=" ")
7. print("World")

8. # Printing formatted output


9. name = "Akif"
10. age = 25
11. print(f"My name is {name} and I am {age} years old.") # f-string formatting
12. print("My name is {} and I am {} years old.".format(name, age)) # format() method

2. Input Statements in Python


Python provides the input() function to take user input as a string.

Syntax:
variable = input(prompt)

 prompt: A message displayed to the user before taking input.


 The input() function always returns a string, so type conversion is needed for numerical inputs.

Examples:
1. # Taking user input
2. name = input("Enter your name: ")
ry.
3. print("Hello, " + name + "!") ra
lib
4. # Taking integer input F
5. age = int(input("Enter your age: "))
PD
on
6. print("You are", age, "years old.")
i
us
cf
7. # Taking float input
8. price = float(input("Enter the price: "))
9. print("The price is", price) y n
ofS
n
3. Advanced Input and Output
sio
e r
v
al
Reading Multiple Inputs:
a, b = map(int, input("Enter two numbers: ").split())ri
print("Sum:", a + b) t
a
ith
Printing Without Newline: w
print("Python", end=" ")
ed
print("is awesome!")
eat
r
Formatted String Output: C
pi = 3.14159
print("Value of pi: {:.2f}".format(pi)) # Using format()
print(f"Value of pi: {pi:.2f}") # Using f-strings

Python Program: Input and Output Statements


1. # Output Statement using print()
2. print("Welcome to Python Programming!")

3. # Taking user input


4. name = input("Enter your name: ") # User enters a string
5. age = int(input("Enter your age: ")) # User enters an integer

6. # Displaying output
7. print(f"Hello, {name}! You are {age} years old.") # Using f-string

8. # Taking multiple inputs in one line


9. num1, num2 = map(int, input("Enter two numbers separated by space: ").split())

10. # Performing addition and displaying result


11. print("Sum of", num1, "and", num2, "is:", num1 + num2)

12. # Demonstrating formatted output


13. pi = 3.14159
14. print("Value of pi up to 2 decimal places: {:.2f}".format(pi))

15. # Printing without a newline


16. print("Python is", end=" ")
17. print("awesome!")

Sample Output:

1. Welcome to Python Programming!


2. Enter your name: Akif
3. Enter your age: 28
4. Hello, Akif! You are 28 years old.
5. Enter two numbers separated by space: 10 20
6. Sum of 10 and 20 is: 30
7. Value of pi up to 2 decimal places: 3.14
8. Python is awesome!

ry.
ra
lib
F
PD
ion
us
n cf
y
ofS
n
sio
e r
v
al
tri
a
ith
w
ed
eat
r
C

Created with a trial version of Syncfusion PDF library or registered the wrong key
in your application. Click here to obtain the valid key.

You might also like