Lab session 3 (1)
Lab session 3 (1)
Department of CS and SE
Perform computations and create logical statements using Python’s operators: Arithmetic,
Assignment, Comparison, Logical, Membership, Identity etc.
Explain how operators are used in Python to execute a specific computation or operation
Write Python code to run different operations on data (e.g. arithmetic calculations
Operators
Operators are the constructs which can manipulate the value of operands. Operators are the constructs
which can manipulate the value of operands.
Consider the expression 4 + 5 = 9. Here, 4 and 5 are called operands and + is called operator.
Types of Operators
Python language supports the following types of operators.
Arithmetic Operators
Comparison (Relational) Operators
Assignment Operators
Logical Operators
Bitwise Operators
Membership Operators
Identity Operators
Arithmetic Operators
Operator Description Example
- Subtraction Subtracts right hand operand from left hand operand. a – b = -10
% Modulus Divides left hand operand by right hand operand and returns b%a=0
remainder
** Exponent Performs exponential (power) calculation on operators a**b =10 to the power 20
Programming Fundamentals
Department of CS and SE
// Floor Division - The division of operands where the result is the 9//2 = 4,
quotient in which the digits after the decimal point are removed. 9.0//2.0 = 4.0,
But if one of the operands is negative, the result is floored, i.e., -11//3 = -4,
rounded away from zero (towards negative infinity) -11.0//3 = -4.0
# Calculations
total_length = length_wall_1 + length_wall_2 # Total wall
length cost_difference = budget_cost - actual_cost # Cost
difference wall_area = length_wall_1 * width_wall # Wall
area cost_per_unit = material_cost / units # Cost per unit
remainder_tiles = total_tiles % workers # Leftover tiles
required_power = machinery_power ** usage_factor # Machinery power
area_per_block, max_blocks = 9, wall_area // 9 # Full-sized blocks
# Display results
print("Total length of the structure:", total_length,
"meters") print("Cost difference:", cost_difference,
"dollars") print("Wall area:", wall_area, "square
meters")
print("Cost per unit:", cost_per_unit, "dollars")
print("Leftover tiles after distribution:",
remainder_tiles) print("Required machinery power:",
required_power) print("Max full-sized blocks fitting
the wall:", max_blocks)
== If the values of two operands are equal, then the condition becomes true. (a == b) is not true.
!= If values of two operands are not equal, then condition becomes true. (a != b) is true.
Programming Fundamentals
Department of CS and SE
<> If values of two operands are not equal, then condition becomes true. (a <> b) is true. This is
similar to != operator.
> If the value of left operand is greater than the value of right operand, (a > b) is not true.
then condition becomes true.
< If the value of left operand is less than the value of right operand, then (a < b) is true.
condition becomes true.
>= If the value of left operand is greater than or equal to the value of right (a >= b) is not true.
operand, then condition becomes true.
<= If the value of left operand is less than or equal to the value of right (a <= b) is true.
operand, then condition becomes true.
# Comparisons
met_target = current_month_sales >= sales_target # Met sales target
sales_improved = current_month_sales > last_month_sales # Improved sales
below_bonus_threshold = current_month_sales < bonus_threshold # Below
bonus threshold
equal_sales = current_month_sales == last_month_sales # Sales remained the same
not_equal_target = current_month_sales != sales_target # Sales not equal to
target
# Display results
print("Met sales target:", met_target)
print("Sales improved from last month:", sales_improved)
print("Sales below bonus threshold:",
below_bonus_threshold) print("Sales remained the same as
last month:", equal_sales) print("Sales not equal to the
target:", not_equal_target)
= Assigns values from right side operands to left side operand c = a + b assigns value
of a + b into c
Programming Fundamentals
Department of CS and SE
+= Add It adds right operand to the left operand and assign the result c += a is equivalent to c
to left operand =c+a
-= Subtract It subtracts right operand from the left operand and assign the c -= a is equivalent to c
result to left operand =c-a
*= Multiply It multiplies right operand with the left operand and assign the c *= a is equivalent to c
result to left operand =c*a
/= Divide It divides left operand with the right operand and assign the c /= a is equivalent to c
result to left operand =c/a
%= Modulus It takes modulus using two operands and assign the result to c %= a is equivalent to c
left operand =c%a
**= Exponent Performs exponential (power) calculation on operators and c **= a is equivalent to c
assign value to the left operand = c ** a
//= Floor Division It performs floor division on operators and assign value to c //= a is equivalent to c
the left operand = c // a
# Using assignment
operators # Assign
remaining materials
remaining_materials = total_materials - materials_used # '='
operator print("Initial remaining materials:", remaining_materials)
Department of CS and SE
print("Remaining materials after today's usage:", remaining_materials)
^ Binary XOR It copies the bit if it is set in one operand but not both. (a ^ b) = 49 (means 0011 0001)
Department of CS and SE
<< Binary The left operands value is moved left by the number of
a << 2 = 240 (means 1111 0000)
Left Shift bits specified by the right operand.
>> Binary The left operands value is moved right by the number of
a >> 2 = 15 (means 0000 1111)
Right Shift bits specified by the right operand.
Department of CS and SE
and Logical AND If both the operands are true then condition becomes true. (a and b) is true.
or Logical OR If any of the two operands are non-zero then condition becomes (a or b) is true.
true.
not Logical NOT Used to reverse the logical state of its operand. Not(a and b) is false.
Description Example
Programming Fundamentals
Department of CS and SE
not in Evaluates to true if it does not finds a variable in the x not in y, here not in results in a 1
specified sequence and false otherwise. if x is not a member of sequence y.
# Customer request
requested_item =
"smartphone"
out_of_stock_item =
"printer"
# Suggestion for
customers if
is_out_of_stock:
print(f"Sorry, '{out_of_stock_item}' is not available. Would you like to
check similar items?")
else:
print(f"'{out_of_stock_item}' is available for purchase.")
is Evaluates to true if the variables on either side of the operator x is y, here is results in 1 if id(x)
point to the same object and false otherwise. equals id(y).
is not Evaluates to false if the variables on either side of the operator x is not y, here is not results in 1
point to the same object and true otherwise. if id(x) is not equal to id(y).
Programming Fundamentals
Department of CS and SE
Operator Description
~+- Complement, unary plus and minus (method names for the last two are +@ and -@)
Department of CS and SE
A payroll system calculates an employee's monthly salary based on their base salary, performance bonus,
and deductions for taxes and benefits. The system uses various operators to compute the final salary.
Understanding operator precedence ensures that the calculations are done correctly and optimally.
Python Code
# Employee data
base_salary = 5000 # Base salary
performance_bonus = 800 # Performance
bonus tax_deductions = 300 # Tax
deductions benefit_deductions = 200 #
Benefit deductions
Department of
CS and SE
Exercise
1. What is the output of the code: 9//2
2. Assumes the variables w, x, y and z are all integers, and that w=5, x=4, y=8 and z=2. What
value will be stored in result after each of the following statements execute?
1. x += y
2. z *= 2
3. y /= z
4. w %= z
1. What happens when Python evaluates the statement x += x - x when x has the value 3?
2. Write the shortest way to express each of the following statements.
1. x = x + 1
2. x = x / 2
3. x = x - (y + 7)
4. x = 2*x
5. number_of_closed_cases = number_of_closed_cases + 2*ncc
3. Write a Python program to solve (x + y) * (x + y) / 2*x.
Test Data: x = 4, y = 3
4. Read two integers from the user and print three lines where:
1. The first line contains the sum of the two numbers.
2. The second line contains the difference of the two numbers (first - second).
3. The third line contains the product of the two numbers.
5. Write a Python program which accepts temperature in Fahrenheit from the user and
convert it into Celsius.
6. Write a Python program to add two positive integers without using the '+' operator. Note: Use
bit wise operations to add two numbers.
7. Consider the following program that attempts to compute the circumference of a circle given the
radius
entered by the user. Given a circle’s radius, r, the circle’s circumference, C is given by the
formula: C
= 2pr
Program:
r = 0
PI = 3.14159
# Formula for the area of a circle given
its radius C = 2*PI*r
# Get the radius from the user
r = float(input("Please enter the circle's
radius: ")) # Print the circumference
print("Circumference is", C)