Unit 2 Python
Unit 2 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.
Program Code:
Now we give code examples of arithmetic operators in Python. The code 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.
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.
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
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.
Program Code:
Now we give code examples of Logical operators in Python. The code is given below -
Now we compile the above code in Python, and after successful compilation, we run it. Then the output is given below -
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.
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.")
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.
Now we give code examples of Identity operators in Python. The code is given below -
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
Syntax:
print(value, ..., sep=' ', end='\n', file=[Link], flush=False)
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")
Syntax:
variable = input(prompt)
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
6. # Displaying output
7. print(f"Hello, {name}! You are {age} years old.") # Using f-string
Sample Output:
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.