Python Practical (4.... 11)
Python Practical (4.... 11)
In Python, operators are special symbols used to perform operations on variables and
values. They are categorized based on the type of operation they perform.
For performing any operation, we generally required operator & Operand where:
1) Arithmetic Operators
2) Comparison Operators
3) Assignment Operators
4) Logical Operators
5) Bitwise Operators
6) Special Operators
7) Identity Operators
8) Membership Operators
1. Arithmetic Operators: -
Arithmetic operators are used to performing mathematical operations like addition,
subtraction, multiplication, and division, floor division, Modulus division.
+ Addition 5+5 10
- Subtraction 5-3 2
* Multiplication 5*5 25
/ Division 10/5 2.0
% Modulus Division 10%5 0
OUTPUT:
Enter the value for a:10
Enter the value for b:5
Addition: 15
Subtraction: 5
Multiplication: 50
Division: 2.0
Floor division: 2
Modulus: 0
Power: 100000
2. Comparison / Relational Operators: -
In Python comparison operators also known as Relational operators which are used to
compare values. They return either True or False depending on the comparison result.
== Equal to 5 == 5 True
Example: -
# Program to demonstrate the Comparison / relational operations
a = 10
b = 20
print (a == b) # False
print(a != b) # True
print(a > b) # False
print(a < b) # True
print(a >= b) # False
print(a <= b) # True
OUTPUT:
False
True
False
True
False
True
3. Assignment Operators: -
Assignment operators are used to store values in variables. The simplest one is =, which
assigns the value on the right to the variable on the left.
Example: -
x = 10 # x = 10
print(x)
x += 5 # x = x + 5 → x becomes 15
print(x)
x *= 2 # x = x * 2 → x becomes 30
print(x)
x -= 4 # x = x - 4 → x becomes 26
OUTPUT:
10
15
30
4. Logical Operators :-
Logical operators are used to combine multiple conditions (usually Boolean
expressions). They return True or False based on the logic of the expressions.
and Returns True if both are True 5 > 2 and 3 < 4 True
Example: -
# Program to demonstrate the logical operations
a = 10
b = 5
c = 7
print(a > b and b < c)
# True: 10 > 5 AND 5 < 7
OUTPUT:
True
True
False
5. Bitwise Operators: -
Bitwise operators perform operations on binary representations of integers.
Example: -
<< (Left Shift): Shifts bits to the left, adding zeroes on the right.
Example: 5 << 1 # 10 (binary: 0101 << 1 = 1010)
>> (Right Shift): Shifts bits to the right, discarding bits on the right.
Example: 5 >> 1 # 2 (binary: 0101 >> 1 = 0010)
6. Special Operators: -
While not a standard category in Python documentation, "special operators" often
refer to identity and membership operators, as they are used in special situations
(like comparing memory or testing membership).
You can consider the identity and membership sections above as the complete
breakdown of special operators.
1. Identity Operators: -
Identity operators are used to compare the memory location of two objects. They
return True if both variables refer to the same object in memory.
Example: -
# Program to demonstrate identity operators
x = [1, 2, 3]
y = x
z = [1, 2, 3]
print(x is y)
# True: x and y point to the same object in memory
print(x is z)
# False: x and z have the same values but different memory
locations
print(x is not z)
# True: x and z are not the same object
2. Membership Operators: -
Membership operators are used to test whether a value is a member of a sequence
(like string, list, tuple, etc.). They return True or False.
Example: -
# Program to demonstrate membership operators
nums = [1, 2, 3, 4]
print(3 in nums)
# True: 3 is in the list
Control Structure
nested-if
Syntax:
if condition:
# code block
CODE:-
# Program to demonstrate If statement
i = 10
if (i > 5):
print("5 is less than 10")
print ("I am Not in if")
OUTPUT:
5 is less than 10
I am Not in if
b) if-else statement:
When condition is True then Print if block otherwise print else block.
Syntax:
if condition:
# block A
else:
# block B
CODE:-
# Program to demonstrate if-else statement
i = 20
if (i < 15):
print("15 is smaller than i")
else:
print("i is greater than 15")
OUTPUT:
i is greater than 15
c) if-elif-else:
Syntax:
if condition1:
# block A
elif condition2:
# block B
else:
# block C
CODE: -
# Program to demonstrate if-elif-else statement
i = 15
if (i == 10):
print("i is 10")
elif (i == 15):
print("i is 15")
elif (i == 20):
print("i is 20")
else:
print("i is out of range")
OUTPUT:
i is 15
d) nested-if:
Checks multiple conditions in sequence
Syntax:
if (condition1):
if (condition2):
CODE:-
# Program to demonstrate nested-if statement
i = 10
# 1st if block
if (i == 10):
# 2nd if block
if (i > 5):
print("i is greater than 5")
else:
print("I is out of range")
OUTPUT:
i is 15
6] WAP to demonstrate the control statements in python.
CODE:-
# Program to demonstrate break statement
colour= ["Red","Green","Pink","Orange"]
for clr in colour:
print(clr)
if clr=="Green":
break
OUTPUT:
Red
Green
CODE:-
# Program to demonstrate continue statement
colour= ["Red","Green","Pink","Orange"]
if clr=="Pink":
continue
print(clr)
OUTPUT:
Red
Green
Orange
CODE:-
# Program to demonstrate pass statement
for i in range(0,6):
pass
OUTPUT:
No Output
7] WAP to demonstrate the Looping statements in python.
a) for loop
A for loop is used for iterating over a sequence (that is either a list, a tuple, a dictionary,
a set, or a string).
This is less like the for keyword in other programming languages, and works more like
an iterator method as found in other object-orientated programming languages.
With the for loop we can execute a set of statements, once for each item in a list, tuple,
set etc.
Syntax: OUTPUT:
for variable in sequence: 0
# block of code to execute
1
2
CODE:- 3
# Program to demonstrate While loop 4
n=5
for i in range(0,n):
print(i)
b) Nested Loops
Python programming language allows to use one loop inside another loop.
In the following program, we have created two different lists [i.e clr & frt] and tried to
access elements from them in a nested form.
Syntax :
for variable in sequence:
for variable in sequence:
# block of code to execute
CODE:-
# Program to demonstrate nested loop
clr=["red","green","pink"]
frt=["apple","banana","cherry"]
for x in clr:
for y in frt:
print(x,y)
OUTPUT:
red apple
red banana
red cherry
green apple
green banana
green cherry
pink apple
pink banana
pink cherry
c) while loop
In python, while loop is used to execute a block of statements repeatedly
until a given condition is satisfied. And when the condition becomes false,
the line immediately after the loop in the program is executed.
Syntax :
while expression:
statement(s)
OUTPUT:
CODE:- 0
- Lists are just like dynamically sized arrays, declared in other languages.
- Lists need not be homogeneous always which makes it the most powerful tool in
Python. A single list may contain DataTypes like Integers, Strings, as well as
Objects.
- Lists are mutable i.e. can be modify after creation. The same item can appear
more than once, and each has its own place.
- A list in Python is ordered and has a fixed number of elements. Each item has a
position (index) starting from 0.
Creating a List:
Lists in Python can be created by just placing the sequence inside the square
brackets[]. Unlike Sets, a list doesn’t need a built-in function for the creation of a list.
CODE:-
# Python program to demonstrate Creation of List
# Creating a List
List = []
print("Blank List: ",List)
List of numbers:
[10, 20, 14]
List Items:
Hello
Hello
Multi-Dimensional List:
[['Hello', 'World'], ['Hello']]
pop() – Removes item by index and returns it. (last item by default).
list:",list)
list.insert(0, 25)
print("Inserting element:",
list)
list.append(30)
print("Appendding item:",
list)
list.extend([40, 50])
print("Extending list:", list)
index = list.index(50)
print("Index of 50:", index)
count = list.count(40)
print("Count of 40:", count)
list.sor
t()
print("Sorting List:", list)
list.reverse()
print("Reversing list:",
list)
copied_list = list.copy()
print("Copied list:", copied_list)
list.remove(
25)
print("Removing element:", list)
popped = list.pop()
print("After pop:", list)
print("Popped item:",
popped)
list.clea
r()
print("Clearing list:", list)
OUTPUT:
Creating blank list: []
Inserting element: [25]
Appendding item: [25, 30]
Extending list: [25, 30, 40, 50]
Index of 50: 3
Count of 40: 1
Sorting List: [25, 30, 40, 50]
Reversing list: [50, 40, 30, 25]
Copied list: [50, 40, 30, 25]
Removing element: [50, 40, 30]
After pop: [50, 40]
Popped item: 30
Clearing list: []
➢ List Comprehension
- List comprehensions are used for creating new lists from other iterables like
tuples, strings, arrays, lists, etc.
- A list comprehension consists of brackets containing the expression, which is
- executed for each element along with the for loop to iterate over each element.
Example:
evens = [x for x in range(1, 21) if x % 2 == 0]
print(evens)
# OUTPUT [2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
9] WAP to demonstrate Dictionary data type.
❖Dictionary in Python
A dictionary in Python is a collection of key-value pairs.
It is changeable unordered collection of data types, and indexed by keys.
Each key must be unique, and it is associated with a value.
Key-value is provided in the dictionary to make it more optimized.
➢ Creating a Dictionary
- In Python, a Dictionary can be created by placing a sequence of elements within
curly {} braces, separated by ‘comma’.
- Values in a dictionary can be of any data type and can be duplicated, whereas
keys can’t be repeated and must be immutable.
- Dictionary keys are case sensitive, the same name but different cases of Key will
be treated differently.
Followings are the methods of dictionary
➢ clear() – Removes all items from the dictionary.
➢ pop() – Removes the element from the dictionary. (By default it delete last
element).
➢ popitem() – Removes and returns the last key-value pair from the dictionary.
➢ setdefault() – Returns the value of a specified key. If the key doesn’t exist, inserts
the key with the specified value.
➢ update() – Updates the dictionary with key-value pairs from another dictionary
or iterable.
CODE:-
# Creating blank dictionary
my_dict = {}
my_dict['Name'] = 'Payal'
my_dict['Age'] = 25
my_dict['Name'] = 'Priyanka'
my_dict.clear()
Clearing dictionary: {}
10] WAP to demonstrate Set data type.
Sets in Python
- A set in Python is a collection of unique elements.
- It is an unordered, mutable (changeable) data type that does not allow
duplicate values.
- Sets are useful for performing mathematical set operations like union,
intersection, and difference.
- Elements of a set must be immutable (numbers, strings, tuples), but the set
itself is mutable (we can add or remove items).
Creating a Set
- In Python, a set can be created by placing elements inside curly braces {},
separated by commas. Duplicate values are automatically removed.
Difference() – Returns elements present in the first set but not in the second.
CODE:-
# Creating a blank set my_set = set() print("Creating a blank set:", my_set)
# Creating a set with values
my_set = {1, 2, 3, 4, 4, 5} # Duplicate '4' will be removed print("Set with
unique elements:", my_set)
OUTPUT:
Popped element: 1
A = {1, 2, 3}
B = {3, 4, 5}
# common element
# present in a not in b
Syntax:
variable = input("Message shown to user") Example:
Example:
#converts string input into integer
age = int(input("Enter age:"))
print(age)
OUTPUT:
Enter your age: 24
24
➢ Output in Python
Output refers to the information displayed to the user. In Python, output is
shown using the print() function.
Syntax:
print(variable) # For numeric
Print(#Statement)
Example:
print("Hello", "World") # Output: Hello World
print("Hello", "World", sep="-") # Output: Hello-World
print("Hello", end="!") # Output: Hello!
➢ Output Formatting
Output formatting allows us to display results in a readable and user-friendly
way. Simply , we can say that the user can display the result as per their need
A. f-strings
B. format() method
C. Formatting Numbers
12] WAP to demonstrate function and types of function argument