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

Lab session 3 (1)

This document outlines a lab session focused on Python operators, detailing their types and applications, including arithmetic, comparison, assignment, logical, membership, and identity operators. It provides practical examples and Python code snippets for various scenarios, such as resource management in construction projects and sales performance analysis. The document emphasizes the importance of understanding and utilizing these operators for effective programming and data manipulation.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Lab session 3 (1)

This document outlines a lab session focused on Python operators, detailing their types and applications, including arithmetic, comparison, assignment, logical, membership, and identity operators. It provides practical examples and Python code snippets for various scenarios, such as resource management in construction projects and sales performance analysis. The document emphasizes the importance of understanding and utilizing these operators for effective programming and data manipulation.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 11

Programming Fundamentals

Department of CS and SE

Lab Session 3: Operators


Learning Outcomes
After this lab, students will be able to:

 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

+ Addition Adds values on either side of the operator. a + b = 30

- Subtraction Subtracts right hand operand from left hand operand. a – b = -10

* Multiplication Multiplies values on either side of the operator a * b = 200

/ Division Divides left hand operand by right hand operand b/a=2

% 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

Efficient Resource Management in Construction Project Using Python


Arithmetic Operators
In a construction project, the team calculates wall dimensions, material usage, and costs. They determine
the total wall length, cost differences, wall area, material cost per unit, leftover tiles, machinery power
requirements, and the number of blocks fitting a wall. These calculations aid in efficient resource
planning.
Python Code
# Input data
length_wall_1, length_wall_2 = 20, 30 # Wall lengths in
meters budget_cost, actual_cost = 10000, 8700 # Costs in
dollars width_wall, material_cost, units = 5, 2400, 12
total_tiles, workers = 50, 8
machinery_power, usage_factor = 10, 3

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

Python Comparison Operators


These operators compare the values on either sides of them and decide the relation among them. They
are also called Relational operators.

Operator Description Example

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

Analyzing Sales Performance Using Python Comparison Operators


The sales team of a retail company uses Python comparison operators to analyze monthly sales
performance and determine whether goals are met, comparisons with previous months, and eligibility for
bonuses. These relational operators help evaluate relationships between sales data and predefined targets.
Python Code
# Monthly sales data
current_month_sales = 9500
last_month_sales = 10500
sales_target = 10000
bonus_threshold = 12000

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

Python Assignment Operators


Operator Description Example

= 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

Tracking Resource Allocation in a Project Using Python Assignment


Operators
A project manager tracks resource allocation for an ongoing construction project. Using Python
assignment operators, they adjust the available resources dynamically based on project updates. This
includes allocating additional resources, deducting used resources, calculating remaining material needs,
and determining projected usage over time.
Python Code
# Initial resources and allocations
total_materials = 500 # Total materials
available materials_used = 200 # Materials
used initially daily_usage_rate = 50 # Daily
material usage
project_duration_days = 10 # Remaining project duration

# Using assignment
operators # Assign
remaining materials
remaining_materials = total_materials - materials_used # '='
operator print("Initial remaining materials:", remaining_materials)

# Add additional materials received


remaining_materials += 50 # equivalent to: remaining_materials =
remaining_materials
+ 50
print("Remaining materials after restocking:", remaining_materials)

# Deduct materials used for today's tasks


remaining_materials -= daily_usage_rate # equivalent to: remaining_materials
= remaining_materials - daily_usage_rate
Programming Fundamentals

Department of CS and SE
print("Remaining materials after today's usage:", remaining_materials)

# Calculate estimated materials needed for the project


estimated_materials_needed = daily_usage_rate *
project_duration_days print("Estimated materials needed:",
estimated_materials_needed)

# Update estimated materials using multiplication


estimated_materials_needed *= 1.1 # Adding 10% contingency, equivalent
to: estimated_materials_needed = estimated_materials_needed * 1.1
print("Updated materials needed with contingency:", estimated_materials_needed)

# Divide remaining materials equally among workers


workers = 5
materials_per_worker = remaining_materials // workers # Floor division
assignment print("Materials allocated per worker:", materials_per_worker)

# Update remaining materials with modulus operation


remaining_materials %= workers # equivalent to: remaining_materials
= remaining_materials % workers
print("Materials left after equal allocation:", remaining_materials)

# Calculate power usage for machines


power_per_day = 2
total_power = power_per_day
total_power **= project_duration_days # Exponential assignment: total_power
= total_power ** project_duration_days
print("Total power required for the project:", total_power)

Python Bitwise Operators


Bitwise operator works on bits and performs bit by bit operation. Assume if a = 60; and b = 13; Now in
the binary format their values will be 0011 1100 and 0000 1101 respectively. Following table lists out
the bitwise operators supported by Python language with an example each in those, we use the above
two variables (a and b) as operands.

Operator Description Example

& Binary Operator copies a bit to the result if it exists in both


(a & b) (means 0000 1100)
AND operands

| Binary OR It copies a bit if it exists in either operand. (a | b) = 61 (means 0011 1101)

^ Binary XOR It copies the bit if it is set in one operand but not both. (a ^ b) = 49 (means 0011 0001)

~ Binary Ones (~a ) = -61 (means 1100 0011 in


Complement It is unary and has the effect of 'flipping' bits. 2's complement form due to a
signed binary number.
Programming Fundamentals

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.

Managing Hardware Configuration Using Python Bitwise Operators


A robotics team is configuring microcontroller settings for a robot. The team uses Python bitwise
operators to manipulate binary data, such as setting, clearing, toggling, and shifting configuration flags,
which represent the robot's operational modes and hardware status. This ensures efficient memory usage
and direct control over binary-level operations.
Python Code

# Initial binary configurations


a = 60 # Binary: 0011 1100
b = 13 # Binary: 0000 1101

# Bitwise AND: Determine common configuration


flags common_flags = a & b # Binary: 0000 1100
print("Common configuration flags (a & b):", common_flags)

# Bitwise OR: Combine configuration flags


combined_flags = a | b # Binary: 0011
1101
print("Combined configuration flags (a | b):", combined_flags)

# Bitwise XOR: Identify differing configuration flags


differing_flags = a ^ b # Binary: 0011 0001
print("Differing configuration flags (a ^ b):", differing_flags)

# Bitwise NOT: Invert the flags in `a`


inverted_flags = ~a # Binary: 1100 0011 in 2's complement
print("Inverted configuration flags (~a):", inverted_flags)

# Left Shift: Increase precision by shifting bits left


left_shifted = a << 2 # Binary: 1111 0000
print("Left-shifted configuration (a << 2):", left_shifted)

# Right Shift: Reduce precision by shifting bits right


right_shifted = a >> 2 # Binary: 0000 1111
print("Right-shifted configuration (a >> 2):", right_shifted)

# Demonstrating practical use: Checking individual


bits mask = 1 # Binary: 0000 0001
flag_status = (a & mask) # Check if the least significant bit is
set print("Is the least significant bit set in `a`?", flag_status !=
0)

Python Logical Operators


Logical operators are used to combine conditional statements.
Programming Fundamentals

Department of CS and SE

Operator Description Example

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.

Evaluating Access Control in a Secure System Using Python Logical


Operators
A company implements a secure access control system for its data servers. The system uses logical
operators to verify whether a user meets multiple conditions to gain access. Conditions include valid
credentials, membership in an authorized group, and active account status. Logical operators allow the
system to evaluate these criteria efficiently.
Python Code
# User details
valid_credentials =
True
is_authorized_group_member = True
is_account_active = False

# Access control using logical operators


# Check if all conditions are true (Logical AND)
grant_access = valid_credentials and is_authorized_group_member and
is_account_active print("Access granted (AND condition):", grant_access)

# Check if any condition is true (Logical OR)


requires_attention = not valid_credentials or not is_account_active
print("Does the account require attention (OR condition)?", requires_attention)

# Negate access status (Logical NOT)


access_denied = not grant_access
print("Access denied (NOT condition):", access_denied)

# Compound condition: Grant partial access if credentials are valid OR the


account is active
partial_access = valid_credentials or is_account_active
print("Partial access granted (OR condition):",
partial_access)

Python Membership Operators


Python’s membership operators test for membership in a sequence, such as strings, lists, or tuples. There
are two membership operators as explained below.

Description Example
Programming Fundamentals

Department of CS and SE

in Evaluates to true if it finds a variable in the specified x in y, here in results in a 1 if x is a


sequence and false otherwise. member of sequence y.

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.

Checking Inventory Availability in an Online Store Using Python


Membership Operators
An online store uses Python membership operators to check whether a product is available in the
inventory or needs restocking. This functionality is critical for updating the product page and providing
accurate information to customers about the availability of items.
Python Code
# Inventory of available products
inventory = ["laptop", "smartphone", "tablet", "headphones", "camera"]

# Customer request
requested_item =
"smartphone"
out_of_stock_item =
"printer"

# Check if the requested item is in the inventory


is_available = requested_item in inventory
print(f"Is '{requested_item}' available in inventory?", is_available)

# Check if the out-of-stock item is not in the inventory


is_out_of_stock = out_of_stock_item not in inventory
print(f"Is '{out_of_stock_item}' out of stock?", is_out_of_stock)

# 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.")

Python Identity Operators


Identity operators compare the memory locations of two objects. There are two Identity operators
explained below.

Operator Description Example

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

Validating Cache References in a Web Application Using Python Identity


Operators
A web application uses caching to store frequently accessed data objects. The system needs to validate
whether two references point to the same cache object or different ones to optimize performance and
avoid unnecessary computations. Python identity operators (is and is not) are used to perform these
validations efficiently.
Python Code
# Cached objects in a web application
cache_a = {"user_id": 101, "name": "Alice", "role": "admin"}
cache_b = {"user_id": 102, "name": "Bob", "role": "editor"}
cache_c = cache_a # Assign cache_a to cache_c (both refer to the same object)

# Check if cache_a and cache_b are the same


object same_object = cache_a is cache_b
print("Do cache_a and cache_b refer to the same object?", same_object)

# Check if cache_a and cache_c are the same object


same_object_cache = cache_a is cache_c
print("Do cache_a and cache_c refer to the same object?", same_object_cache)

# Check if cache_a and cache_b are not the same object


different_object = cache_a is not cache_b
print("Do cache_a and cache_b refer to different objects?", different_object)

# Modifying cache_c and checking its effect on cache_a


cache_c["role"] = "superadmin"
print("Updated cache_a:", cache_a) # Reflects the change as cache_c refers
to the same object
print("Cache_b remains unchanged:", cache_b)

Python Operators Precedence


The following table lists all operators from highest precedence to lowest.

Operator Description

** Exponentiation (raise to the power)

~+- Complement, unary plus and minus (method names for the last two are +@ and -@)

* / % // Multiply, divide, modulo and floor division

+- Addition and subtraction

>> << Right and left bitwise shift

& Bitwise 'AND'td>


Programming Fundamentals

Department of CS and SE

^| Bitwise exclusive `OR' and regular `OR'

<= < > >= Comparison operators

<> == != Equality operators

= %= /= //= -= += *= Assignment operators


**=

is is not Identity operators

in not in Membership operators

not or and Logical operators

Operator precedence affects how an expression is evaluated.


For example, x = 7 + 3 * 2; here, x is assigned 13, not 20 because operator * has higher precedence than
+, so it first multiplies 3*2 and then adds into 7.
Here, operators with the highest precedence appear at the top of the table, those with the lowest appear at
the bottom.

Evaluating an Employee Salary Calculation in a Payroll System Using Python


Operator Precedence

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

# Calculating the final salary using operators


final_salary = base_salary + performance_bonus - tax_deductions * 2 +
benefit_deductions // 2
print("The final salary of the employee is:", final_salary)

# Checking the order of operations in a more complex expression


x = 7 + 3 * 2 # Multiplication has higher precedence than addition
print("Value of x:", x) # Output should be 13, not 20

# Another example with multiple operators


y = (base_salary + performance_bonus) * (tax_deductions // 100) ** 2
print("Calculated value of y:", y) # Follows the precedence: exponentiation,
then division, then addition and multiplication
Programming Fundamentals

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)

1. The program does not produce the intended result. Why?


2. How can it be repaired so that it works correctly?

You might also like