0% found this document useful (0 votes)
14 views

Module_2[1]

Uploaded by

Ram Deepak
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views

Module_2[1]

Uploaded by

Ram Deepak
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 40

Module-2

Operators and its precedence, Arithmetic Operators, Comparison (Relational)


Operators, Assignment Operators, Logical Operators, Bitwise Operators,
Membership Operators, Identity Operators, Branching Statements-if; if else, nested
if; nested if else, elif

01-07-2024 Dr. V.Srilakshmi 1


Python Operators
• Operators are used to perform operations on variables(operands).
Python provides the following operators:
1. Arithmetic operators
2. Assignment operators
3. Comparison operators
4. Logical operators
5. Identity operators
6. Membership operators
7. Bitwise operators

01-07-2024 Dr. V.Srilakshmi 2


Arithmetic Operators
• Arithmetic operators are used with numeric values to perform
common mathematical operations

01-07-2024 Dr. V.Srilakshmi 3


Arithmetic Operators
x=5
y=2 Output:
print('Addition=',x+y) Addition= 7
print('subtraction =',x-y) subtraction = 3
print('multiplication =',x*y) multiplication = 10
division = 2.5
print('division =',x/y)
Floor dvision = 2
print('Floor dvision =',x//y) Remainder = 1
print('Remainder =',x%y) Exponentiation = 25
print('Exponentiation =',x**y)

01-07-2024 Dr. V.Srilakshmi 4


Assignment Operators
• Assignment operators are used to assign values to variables:

01-07-2024 Dr. V.Srilakshmi 5


Comparison/Relational Operators
• Comparison operators are used to compare two values:
• It either returns True or False according to the condition.

01-07-2024 Dr. V.Srilakshmi 6


Comparison Operators
x = 10
y = 12
print('x > y is',x>y)
print('x < y is',x<y)
print('x == y is',x==y)
print('x != y is',x!=y)
print('x >= y is',x>=y)
print('x <= y is',x<=y)

01-07-2024 Dr. V.Srilakshmi 7


Logical Operators
• Logical operators are used to combine conditional statements

Ex:
x=5

print(x > 3 and x < 4)


print(x > 3 or x < 4)
print(not(x==5))

Output:
False
True
False
01-07-2024 Dr. V.Srilakshmi 8
Membership operators
• They are used to test whether a value or variable is found in a
sequence (string, list, tuple, set and dictionary).
• In a dictionary we can only test for presence of key, not the
value.

01-07-2024 Dr. V.Srilakshmi 9


Membership operators
x = 'Hello world'
print('H' in x)
print('S' in x)
Output:
print('Hello' not in x) True
False
False

01-07-2024 Dr. V.Srilakshmi 10


Bitwise operators
• These operators act upon the individual bits (0 & 1) of their
operands.
• It operates bit by bit, hence the name.
• For example, 2 is 10 in binary and 7 is 111.

1. Bitwise AND (&)


2. Bitwise OR (|)
3. Bitwise XOR (^)
4. Bitwise Complements (~)
5. Bitwise Left shift (<<)
6. Bitwise Right shift (>>)

01-07-2024 Dr. V.Srilakshmi 11


Bitwise operators
int x=10; int y=11;
X: 0000 1010
Y: 0000 1011
X&Y : 0000 1010
result is 10

X: 0000 1010
Y: 0000 1011
X|Y : 0000 1011
result is 11

X: 0000 1010
Y: 0000 1011
X^Y : 0000 0001
result is 1

a = 0011
~a = 1100
01-07-2024 Dr. V.Srilakshmi 12
Bitwise operators
Bitwise Left Shift Operator «
• This operator shifts the bits of the number towards left a
specified number of positions.

X<<n=x*2n

X=10;
X<<2=10x22
=10x4= 40

Bitwise Right Shift Operator (»)


• This operator shifts the bits of the number towards right a
specified number of positions.
X=10;
X>>n=x/ 2n
X>>2=10/22
=10/4=2
01-07-2024 Dr. V.Srilakshmi 13
Identity operators
• is and is not are the identity operators in Python.

Ex:
a1 = 3
b1 = 3

print(a1 is b1)
print(a1 is not b1)

01-07-2024 Dr. V.Srilakshmi 14


Precedence and Associativity of Operators in Python

• Operators have different levels of precedence, which determine the order in which
they are evaluated.
• When multiple operators are present in an expression, the ones with higher
precedence are evaluated first.
• In the case of operators with the same precedence, their associativity comes into play,
determining the order of evaluation.

What is the value of below expression?


10 + 20 * 30

01-07-2024 Dr. V.Srilakshmi 15


Precedence and Associativity of Operators in Python
Precedence Operators Description Associativity
1 () Parentheses Left to right
2 ** Exponentiation Right to left
3 ~x bitwise NOT Right to left
Multiplication, matrix, division, floor division,
4 *, @, /, //, % Left to right
remainder
5 +, – Addition and subtraction Left to right
6 <<, >> Shifts Left to right
7 & Bitwise AND Left to right
8 ^ Bitwise XOR Left to right
9 | Bitwise OR Left to right
in, not in, is, is
10 Comparisons, membership tests, identity tests Left to Right
not, <, <=, >, >=, !=, ==
11 and logical AND Left to right
12 or Logical OR Left to right
01-07-2024 Dr. V.Srilakshmi 16
Ch .Venkata RamiReddy
18 := Department Of Computer Science and Engineering
Assignment expression (walrus operator) Right to left
Precedence and Associativity of Operators in Python
2. 100 / 10 * 10

In this expression ‘*’ and ‘/’ have the same precedence and their
associativity is Left to Right,
so the expression “100 / 10 * 10” is evaluated as

=(100 / 10) * 10

=10*10
value=100
3. What is the value of 100 + 200 / 10 - 3 * 10

4. What is the value of 4+3*2&4|6

01-07-2024 Dr. V.Srilakshmi 17


What is the value of 100 + 200 / 10 - 3 * 10

1.First, perform the multiplication and division:


1. 200 / 10 = 20
2. 3 * 10 = 30
2.Then, perform the addition and subtraction from left to right:
1. 100 + 20 = 120
2. 120 - 30 = 90
So, the value of the expression "100 + 200 / 10 - 3 * 10" is 90.

What is the value of 4+3*2&4|6

1.Multiplication: 3 * 2 = 6
2.Addition: 4 + 6 = 10
3.Bitwise AND: 10 & 4 = 0 (In binary, 10 is 1010 and 4 is 0100. The result of a bitwise AND is 0 where there
are differing bits.)
4.Bitwise OR: 0 | 6 = 6 (In binary, 0 is 0000 and 6 is 0110. The result of a bitwise OR is 1 where there is at
least one 1.)
So, the final result of the expression is 6.

01-07-2024 Dr. V.Srilakshmi 18


Evaluate the expression step by step according to operator precedence and
associativity and print the final output for x = 10 and y = 50 x ** 2 > 100 and y < 100

Let's evaluate it step by step:


1.Evaluate x ** 2:
•x = 10
•x ** 2 = 10 ** 2 = 100
2.Evaluate y < 100:
•y = 50
•y < 100 is true because 50 is indeed less than 100.
3.Now, we have 100 > 100 and True. To evaluate the and operator, we need both
sides to be True for the whole expression to be True. Since the first part, 100 > 100,
is False (because 100 is not greater than 100), the whole expression is False.
So, the final output for x = 10 and y = 50 is False.

01-07-2024 Dr. V.Srilakshmi 19


• 1. Write python program to print your college name

print(“VIT-AP”)

• output:

• 2. Write python program to print your name and college name

print(“name”)

print(“collegename”)

• output:

01-07-2024 Dr. V.Srilakshmi 20


4. write python program to read an integer and display it on the screen

x=int(input(“enter any no:”))

print(x)

• output:

• write python program to assign multiple objects to multiple variables and display on the screen

a=10

b=45.78

c=”Hello”

print(“a=”,a)

print(“b=”,b)

print(“c=”,c)

• output:

01-07-2024 Dr. V.Srilakshmi 21


• write a python program to illustrate the use of membership operators

x=[10,20,30]

print(10 in x)

print(60 in x)

print(10 not in x)

print(60 not in x)

output:

01-07-2024 Dr. V.Srilakshmi 22


1. Write a python program which prompts a user to enter the Basic salary to
calculate the Total salary of an Employee considering the bonus and
conveyance offered to him. Display the Total salary with two digits after the
decimal point.
HRA = 20% of Basic
DA = 105 % of Basic
Conveyance = Rs1300
Bonus = Rs1000

2. Write a Python program to convert kilometers to miles.


Hint: Conversion factor: 1 kilometer = 0.621371 miles

01-07-2024 Dr. V.Srilakshmi 23


• Code1:
# Get the basic salary from the user

basic_salary = float(input("Enter the Basic salary: "))

hra = 0.20 * basic_salary


da = 1.05 * basic_salary
conveyance = 1300
bonus = 1000
total_salary = basic_salary + hra + da + conveyance + bonus

print(f"Total Salary: {total_salary:.2f}")


01-07-2024 Dr. V.Srilakshmi 24
Write a Python program to convert kilometers to miles.
Hint: Conversion factor: 1 kilometer = 0.621371 miles

kilometers = float(input("Enter distance in kilometers: "))


# Conversion factor: 1 kilometer = 0.621371 miles
conversion_factor = 0.621371
miles = kilometers * conversion_factor
print(kilometers, "kilometers is equal to",miles, "miles")

01-07-2024 Dr. V.Srilakshmi 25


Write a Python program to display calendar.

import calendar
year = int(input("Enter year: "))
month = int(input("Enter month: "))
cal = calendar.month(year, month)
print(cal)

01-07-2024 Dr. V.Srilakshmi 26


Decision making (or) conditional Statements
• Decision making is required when we want to execute a code
only if a certain condition is satisfied.
1. The if statement
2. The if else statement
3. if...elif...else Statement
4. Nested if statements

01-07-2024 Dr. V.Srilakshmi 27


if statement
Syntax:
if test expression:
statement(s)

• Here, the program evaluates the test expression and will execute
statement(s) only if the text expression is True.
• If the text expression is False, the statement(s) is not executed.
• In Python, the body of the if statement is indicated by the
indentation.
• Body starts with an indentation and the first unindented line marks
the end.

01-07-2024 Dr. V.Srilakshmi 28


if statement
num = 3
if num>0:
print(num, "is a positive number.")
print("This is always printed.")

01-07-2024 Dr. V.Srilakshmi 29


if...else Statement
Syntax:
if test expression:
Body of if
else:
Body of else
• The if..else statement evaluates test expression and will execute
body of if only when test condition is True.
• If the condition is False, body of else is executed.
• Indentation is used to separate the blocks.

01-07-2024 Dr. V.Srilakshmi 30


if...else Statement
no=input("enter number")
no=int(no)
if(no%5==0 and no%11==0):
print("number is divisible by 5 and 11")
else:
print("number is not divisible by 5 and 11")

01-07-2024 Dr. V.Srilakshmi 31


if...elif...else Statement
if condition1:
# Code to be executed if condition1 is True
elif condition2:
# Code to be executed if condition2 is True
else:
# Code to be executed if none of the conditions are True

• if...elif...else Statement allows you to execute different blocks of code based on specified
conditions.

01-07-2024 Dr. V.Srilakshmi 32


if...elif...else Statement
• If the condition for if is False, it checks the condition of the
next elif block and so on.
• If all the conditions are False, body of else is executed.
• Only one block among the several if...elif...else blocks is
executed according to the condition.
• The if block can have only one else block. But it can have
multiple elif blocks.

01-07-2024 Dr. V.Srilakshmi 33


if...elif...else Statement
a=int(input("enter numbers"))
b=int(input("enter numbers"))
c=int(input("enter numbers"))
if(a>b and a>c):
print(a,"is big")
elif b>c:
print(b,"is big")
else:
print(c,"is big")

01-07-2024 Dr. V.Srilakshmi 34


Nested if statement
• We can have a if...elif...else statement inside another
if...elif...else statement. This is called nesting in computer
programming.
Example:
num = int(input("Enter a number: "))
if num >= 0:
if num == 0:
print("Zero")
else:
print("Positive number")
else:
print("Negative number")
01-07-2024 Dr. V.Srilakshmi 35
Practice Exercises:
• Program to display the appropriate message as per the colour of
signal at the road crossing.(Hint: red=“STOP”, orange=“Be slow”
and green=“GO
• Write a program for a score between 0.0 and 1.0. if the score is out
of range, print an error. If the score is between 0.0 and 1.0, print a
grade using the following table.

Score Grade
>=0.9 A
>=0.8 B
>=0.7 C
>=0.6 D
<0.6 F
01-07-2024 Dr. V.Srilakshmi 36
• Write a program to calculate and print the amount
of money to be paid by a customer based on the
details given below in the table. Customer has to
pay 9% GST on the remaining/discounted price(i.e.
MRP- discount) also.(use MRP to take input by the
user during run-time and “Amount” to print the
output) MRP Discount
Upto Rs.2000 5%
Rs.2000 to Rs. 5000 10%
Rs.5000 to Rs. 10000 15%

Above 10000 20%

01-07-2024 Dr. V.Srilakshmi 37


Program to display the appropriate message as per the colour of signal at the road
crossing.(Hint: red=“STOP”, orange=“Be slow” and green=“GO”

Program:
signal=input ("enter signal")
if(signal=="red"):
print("STOP")
elif(signal=="orange"):
print ("Be slow")
elif(signal=="green"):
print ("to go")
else:
print("error")

01-07-2024 Dr. V.Srilakshmi 38


Write a program for a score between 0.0 and 1.0. if the score is
out of range, print an error. If the score is between 0.0 and 1.0,
print a grade using the following table.
Score Grade
Program: >=0.9 A
>=0.8 B
score=float(input("enter score")) >=0.7 C
if(score>=0.9 and score<=1.0):
>=0.6 D
print("A")
elif(score>=0.8 and score<0.9): <0.6 F
print("B")
elif(score>=0.7 and score<0.8):
print("C")
elif(score>=0.6 and score<0.7):
print("D")
elif(score<0.6):
print("F")
else:
print("error")

01-07-2024 Dr. V.Srilakshmi 39


Write a program to calculate and print the amount of money to be paid by a
customer based on the datails given below in the table. Customer has to pay
9% GST on the remaining/discounted price(i.e. MRP- discount) also.(use MRP
to take input by the user during run-time and “Account” to print the output)

Program: MRP Discount


MRP=int(input("enter MRP")) Upto Rs.2000 5%
if(MRP>=1 and MRP<2000):
Rs.2000 to Rs. 5000 10%
discount=0.05*MRP
elif(MRP>=2000 and MRP<5000): Rs.5000 to Rs. 10000 15%
discount=0.1*MRP
elif(MRP>=5000 and MRP<10000): Above 10000 20%
discount=0.15*MRP
elif(MRP>10000):
discount=0.2*MRP
else:
print("error")
amount=MRP-discount
GST=0.09*amount
paidamount=amount+GST
print("MRP Discount GST Paidamount")
print(MRP," ",discount," ",GST," ",paidamount)
01-07-2024 Dr. V.Srilakshmi 40

You might also like