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

Satyam Python 5-Copy

The document outlines Experiment No. 5 for a Mechanical Engineering course, focusing on Python programming concepts including operators, byte and byte arrays, and sets. It provides theoretical explanations and examples for various types of operators such as arithmetic, comparison, assignment, logical, membership, and identity operators, as well as details on working with byte arrays and sets. The document includes programming exercises to demonstrate the application of these concepts.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Satyam Python 5-Copy

The document outlines Experiment No. 5 for a Mechanical Engineering course, focusing on Python programming concepts including operators, byte and byte arrays, and sets. It provides theoretical explanations and examples for various types of operators such as arithmetic, comparison, assignment, logical, membership, and identity operators, as well as details on working with byte arrays and sets. The document includes programming exercises to demonstrate the application of these concepts.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 16

DEPARTMENT OF MECHANICAL ENGINERING

EXPERIMENT NO: 5
NAME OF EXPERIMENT: Programs to study Operators,
Byte and byte arrays and Sets
DATE OF PERFORMANCE: 10/02/2025
DATE OF SUBMISSION: 24/02/2025

Python Programming Lab 1


DEPARTMENT OF MECHANICAL ENGINERING
Experiment No. 5

Programs to study Operators, byte and byte arrays and


Sets
Aim: a) To study Python Operators
b) To study Python bytes ()
c) To study Python byte arrays
d) To study Python Sets

Theory:
a) Python Operators: Arithmetic, Logical, Comparison, Assignment,
Bitwise & Precedence

• Arithmetic Operators
Arithmetic Operators perform various arithmetic calculations like addition, subtraction,
multiplication, division, %modulus, exponent, etc. There are various methods for arithmetic
calculation in Python like you can use the eval function, declare variable & calculate, or call
functions.

Example: For arithmetic operators we will take simple example of addition where we will
add two-digit 4+5=9
x= 4
y= 5
print(x + y)

Similarly, you can use other arithmetic operators like for multiplication(*), division (/),
substraction (-), etc. %

• Comparison Operators
Comparison Operators In Python compares the values on either side of the operand and
determines the relation between them. It is also referred to as relational operators. Various
comparison operators in python are ( ==, != , <>, >,<=, etc.)

Example: For comparison operators we will compare the value of x to the value of y and
print the result in true or false. Here in example, our value of x = 4 which is smaller than y =
5, so when we print the value as x>y, it actually compares the value of x to y and since it is
not correct, it returns false.

Python Programming Lab 2


DEPARTMENT OF MECHANICAL ENGINERING
x=4
y=5
print(('x > y is',x>y)) Likewise, you can try other comparison operators (x < y, x==y, x!=y, etc.)
• Python Assignment Operators

Assignment Operators in Python are used for assigning the value of the right operand to
the left operand. Various assignment operators used in Python are (+=, - = , *=, /= , etc.).

Example: Python assignment operators is simply to assign the value, for example
num1 = 4
num2 = 5
print(("Line 1 - Value of num1 : ", num1))
print(("Line 2 - Value of num2 : ", num2))

Example of compound assignment operator

We can also use a compound assignment operator, where you can add, subtract, multiply
right operand to left and assign addition (or any other arithmetic function) to the left
operand.

• Step 1: Assign value to num1 and num2


• Step 2: Add value of num1 and num2 (4+5=9)
• Step 3: To this result add num1 to the output of Step 2 ( 9+4)
• Step 4: It will print the final result as 13
num1 = 4 num2 =
5 res = num1 +
num2
res += num1
print(("Line 1 - Result of + is ", res))

• Logical Operators
Logical operators in Python are used for conditional statements are true or false. Logical operators
in Python are AND, OR and NOT. For logical operators following condition are applied.

• For AND operator – It returns TRUE if both the operands (right side and left side) are
true
• For OR operator- It returns TRUE if either of the operand (right side or left side) is
true
• For NOT operator- returns TRUE if operand is false

Example: Here in example we get true or false based on the value of a and b
a = True b = False print(('a
and b is',a and b)) print(('a
or b is',a or b)) print(('not
a is',not a))

Python Programming Lab 3


DEPARTMENT OF MECHANICAL ENGINERING
• Membership Operators
These operators test for membership in a sequence such as lists, strings or tuples. There are
two membership operators that are used in Python. (in, not in). It gives the result based on
the variable present in specified sequence or string

Example: For example here we check whether the value of x=4 and value of y=8 is available
in list or not, by using in and not in operators.
x = 4 y = 8 list = [1,
2, 3, 4, 5 ]; if ( x in
list ):
print("Line 1 - x is available in the given list")
else: print("Line 1 - x is not available in the given
list") if ( y not in list ):
print("Line 2 - y is not available in the given list")
else: print("Line 2 - y is available in the given
list")

• Declare the value for x and y


• Declare the value of list
• Use the "in" operator in code with if statement to check the value of x existing in the
list and print the result accordingly
• Use the "not in" operator in code with if statement to check the value of y exist in the
list and print the result accordingly
• Run the code- When the code run it gives the desired output

Identity Operators
Identity Operators in Python are used to compare the memory location of two objects. The
two identity operators used in Python are (is, is not).

• Operator is: It returns true if two variables point the same object and false otherwise
• Operator is not: It returns false if two variables point the same object and true
otherwise

Following operands are in decreasing order of precedence.

Operators in the same box evaluate left to right


Operators (Decreasing order of precedence) Meaning

** Exponent

Python Programming Lab 4


DEPARTMENT OF MECHANICAL ENGINERING
*, /, //, % Multiplication, Division, Floor
division, Modulus

+, - Addition, Subtraction

<= < > >= Comparison operators

= %= /= //= -= += *= **= Assignment Operators

is is not Identity operators

in not in Membership operators

not or and Logical operators

Example:
x = 20 y =
20 if ( x is
y ):
print("x & y SAME identity")
y=30 if ( x is not y ):
print("x & y have DIFFERENT identity")

• Declare the value for variable x and y


• Use the operator "is" in code to check if value of x is same as y
• Next we use the operator "is not" in code if value of x is not same as y
• Run the code- The output of the result is as expected

Operator precedence
The operator precedence determines which operators need to be evaluated first. To avoid
ambiguity in values, precedence operators are necessary. Just like in normal multiplication
method, multiplication has a higher precedence than addition. For example in 3+ 4*5, the
answer is 23, to change the order of precedence we use a parentheses (3+4)*5, now the
answer is 35. Precedence operator used in Python are (unary + - ~, **, * / %, + - , &) etc.

Python Programming Lab 5


DEPARTMENT OF MECHANICAL ENGINERING
The source parameter can be used to initialize the byte array in the following ways:

Different source parameters

Type Description

Converts the string to bytes using str.encode() Must also


String
provide encoding and optionally errors

Integer Creates an array of provided size, all initialized to null

Different source parameters

Type Description

A read-only buffer of the object will be used to initialize the


Object
byte array

Creates an array of size equal to the iterable count and


Iterable initialized to the iterable elements Must be iterable of integers
between 0 <= x < 256

No source
Creates an array of size 0
(arguments)

Return value from bytes():


The bytes() method returns a bytes object of the given size and initialization values.

Python Programming Lab 7


DEPARTMENT OF MECHANICAL ENGINERING

Program b.2) Create a byte of given integer size

INPUT:

OUTPUT:

Python Programming Lab 9


DEPARTMENT OF MECHANICAL ENGINERING

c) Python bytearray()

The bytearray() method returns a bytearray object which is an array of the given bytes.

syntax :
bytearray([source[, encoding[, errors]]])

bytearray() method returns a bytearray object (i.e. array of bytes) which is mutable (can be
modified) sequence of integers in the range 0 <= x < 256.

If you want the immutable version, use bytes() method.

bytearray() Parameters

bytearray() takes three optional parameters:

• source (Optional) - source to initialize the array of bytes.


• encoding (Optional) - if the source is a string, the encoding of the string.
• errors (Optional) - if the source is a string, the action to take when the encoding
conversion fails (Read more: String encoding)
The source parameter can be used to initialize the byte array in the following ways:

Different source parameters

Python Programming Lab 11


DEPARTMENT OF MECHANICAL ENGINERING
Type Description

Converts the string to bytes using str.encode() Must also provide


String
encoding and optionally errors

Creates an array of provided size, all initialized to


Integer
null

A read-only buffer of the object will be used to initialize the byte


Object
array

Creates an array of size equal to the iterable count and initialized


Iterable to the iterable elements Must be iterable of integers between 0 <=
x < 256

No source
(arguments) Creates an array of size 0.

Return value from bytearray() bytearray() method returns an array of bytes of the
given size and initialization values.

Program c.1): Array of bytes from a string


INPUT:

Python Programming Lab 12


DEPARTMENT OF MECHANICAL ENGINERING

OUTPUT:

Program c.2): Array of bytes of given integer size


INPUT:

Python Programming Lab 13


DEPARTMENT OF MECHANICAL ENGINERING
We cannot access or change an element of a set using indexing or slicing. Set data type does
not support it.

We can add a single element using the add() method, and multiple elements using the update()
method. The update() method can take tuples, lists, strings or other sets as its argument. In all
cases, duplicates are avoided.
• Removing elements from a set
A particular item can be removed from a set using the methods discard() and remove().

The only difference between the two is that the discard() function leaves a set unchanged if
the element is not present in the set. On the other hand, the remove() function will raise an
error in such a condition (if element is not present in the set).

Similarly, we can remove and return an item using the pop() method.

Since set is an unordered data type, there is no way of determining which item will be
popped. It is completely arbitrary.

We can also remove all the items from a set using the clear() method.

Python Set Operations

Sets can be used to carry out mathematical set operations like union, intersection, difference
and symmetric difference. We can do this with operators or methods.

Python Programming Lab 17


DEPARTMENT OF MECHANICAL ENGINERING
Difference of the set B from set A(A - B) is a set of elements that are only in A but not in B.
Similarly, B - A is a set of elements in B but not in A. Difference is performed using - operator.
Same can be accomplished using the difference() method.

Program code

Program d.1) Creating python sets


INPUT:

Python Programming Lab 19


DEPARTMENT OF MECHANICAL ENGINERING

Program d.2) Modifying a set in Python

INPUT:

OUTPUT:

Python Programming Lab 21


DEPARTMENT OF MECHANICAL ENGINERING

Program d.4) Removing elements from set using pop(), clear()


INPUT:

OUTPUT:

Python Programming Lab 23


DEPARTMENT OF MECHANICAL ENGINERING

Program d.5) Set Operations: Union, Intersection, difference


INPUT:

Python Programming Lab 24


DEPARTMENT OF MECHANICAL ENGINERING

OUTPUT:

Python Programming Lab 25

You might also like