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

Python Lab Manual 314004 1-15 practical_011518

The document is a lab manual for Python programming that covers installation, key features, applications, and practical exercises involving various programming concepts such as operators, conditional statements, loops, and lists. It includes step-by-step instructions for executing Python programs, examples of code, and explanations of programming constructs. The manual serves as a comprehensive guide for students learning Python at Jamia Polytechnic, Akkalkuwa.

Uploaded by

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

Python Lab Manual 314004 1-15 practical_011518

The document is a lab manual for Python programming that covers installation, key features, applications, and practical exercises involving various programming concepts such as operators, conditional statements, loops, and lists. It includes step-by-step instructions for executing Python programs, examples of code, and explanations of programming constructs. The manual serves as a comprehensive guide for students learning Python at Jamia Polytechnic, Akkalkuwa.

Uploaded by

Huzeefa Pathan
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 41

PYTHON PROGRAMMING (314004) SOLVED LAB MANUAL

Practical No. 1: Install Python IDE


Download Python :
https://www.python.org/downloads/

Download PyCharm:
https://www.jetbrains.com/pycharm/download/#section=windows .

1) Write steps to install python on windows.


https://www.geeksforgeeks.org/how-to-install-python-on-windows/

2) Print the version of Python.

3) List key features of python.


Features in Python
• Free and Open Source. ...
• Easy to code. ...
• Easy to Read. ...
• Object-Oriented Language. ...
• GUI Programming Support. ...
• High-Level Language. ...
• Large Community Support. ...
• Easy to Debug.

4) What are the key features of Python?


https://www.geeksforgeeks.org/python-features/

5) What are the applications of Python?


Python is a versatile programming language with many applications, including:
• Data science: Python is used to analyse and visualize data, conduct statistical calculations,
and build machine learning algorithms

PROF. FIROZKHAN S PATHAN JAMIA POLYTEHCNIC, AKKALKUWA 1


PYTHON PROGRAMMING (314004) SOLVED LAB MANUAL

• Software development: Python is used to develop websites, software, and other


applications
• Task automation: Python is used to automate tasks
• Artificial intelligence: Python is used to develop artificial intelligence applications
• Scientific computing: Python is used for scientific computing, including complex
calculations
• Education: Python is used to teach programming at the introductory and advanced levels
• Everyday tasks: Python is used by non-programmers, such as accountants and scientists,
for everyday tasks like organizing finances
Some examples of Python applications include:
• Data visualization
Python can be used to create plots, add labels and legends, and customize three-
dimensional plots
• Console applications
Python can be used to create command-line applications that use simple text to
complete tasks
• Machine learning
Python can be used to build machine learning algorithms
• Scientific computing
Python can be used for complex calculations, such as those used in machine learning and
artificial intelligence
https://www.python.org/about/apps/

6) State use of pip & pep.


In the Python programming language, "pip" is the package installer used to download and
manage external libraries (packages) from the Python Package Index (PyPI), while "PEP" stands
for "Python Enhancement Proposal" which is a document outlining proposed changes or
improvements to the Python language itself
Key points about pip and PEP:
• Pip:
o Function: Installs and manages third-party Python packages.
o Command usage: pip install <package_name> to install a package.
o Accesses packages from: Python Package Index (PyPI).
• PEP:
o Function: A formal document proposing changes or additions to the Python language.
o Process: PEPs are discussed and reviewed by the Python community before being
implemented.
o Example: PEP 8 - Defines the recommended style guide for Python code.

PROF. FIROZKHAN S PATHAN JAMIA POLYTEHCNIC, AKKALKUWA 2


PYTHON PROGRAMMING (314004) SOLVED LAB MANUAL

Practical No. 2: Write simple Python program to display message on screen


1. List different modes of Programming in Python
In Python, the primary "modes" of programming refer to how you interact with the
Interpreter : Interactive Mode where you type code line-by-line directly, and Script Mode where
you write code in a file (with a .py extension) and execute the entire script at once; essentially,
these are the two ways to run Python code.
• Interactive Mode:
o Useful for testing small snippets of code or quickly experimenting with syntax.
o Access the interpreter directly by typing "python" in the command line.
o Immediate feedback on each line of code executed.
• Script Mode:
o For writing larger, complex programs with multiple lines of code.
o Save your code in a file with a ".py" extension.
o Execute the entire script by running the file name in the command line.

2. State the steps involved in executing the program using Script Mode.
Executing a Python program in script mode involves the following steps:
• Write the Code:
Create a text file using a text editor or an IDE and write your Python code. Save the file
with a .py extension, which signifies a Python script.
• Open a Terminal or Command Prompt:
Navigate to the directory where you saved your Python script using the cd command.
• Execute the Script:
Use the python command followed by the name of your script file.
For example: python myscript.py
• View Output: The Python interpreter will execute your script, and any output produced by
the script will be displayed in the terminal or command prompt window.
https://www.youtube.com/watch?v=swmxFmfHNDY

PROF. FIROZKHAN S PATHAN JAMIA POLYTEHCNIC, AKKALKUWA 3


PYTHON PROGRAMMING (314004) SOLVED LAB MANUAL

3. Write a Python program to display “MSBTE” using Script Mode.

PROF. FIROZKHAN S PATHAN JAMIA POLYTEHCNIC, AKKALKUWA 4


PYTHON PROGRAMMING (314004) SOLVED LAB MANUAL

Practical No. 3: Write simple Python program using operators: Arithmetic


Operators, Logical Operators, Bitwise Operators

1. Describe ternary operator in Python.


The ternary operator is a concise way to write an if-else statement in a single line. It's also
known as a conditional expression. It returns a true or false value by evaluating a boolean
condition.
Syntax : value_if_true if condition else value_if_false
Example :

2. Describe about different Bitwise operators in Python with appropriate examples.


Bitwise Operators: Python bitwise operators are used to perform bitwise calculations on
integers. The integers are first converted into binary and then operations are performed on each
bit or corresponding pair of bits, hence the name bitwise operators. The result is then returned
in decimal format.

Bitwise Operators in Python | Right-shift, Left-shift, AND, OR, NOT, XOR | Python
https://www.youtube.com/watch?v=Yk3Jwm5YuFs

PROF. FIROZKHAN S PATHAN JAMIA POLYTEHCNIC, AKKALKUWA 5


PYTHON PROGRAMMING (314004) SOLVED LAB MANUAL

3. Describe about different Logical operators in Python with appropriate examples.


Logical Operators: Python logical operators are used to combine conditional statements,
allowing you to perform operations based on multiple conditions. These Python operators,
alongside arithmetic operators, are special symbols used to carry out computations on values
and variables.
• Logical AND : Returns True if both the operands are true
• Logical OR : If any of the two operands are non-zero then condition becomes true
• Logical NOT : Used to reverse the logical state of its operand
Example :

4. Write a program to find the square root of a number.

5. Write a program to convert bits to Megabytes, Gigabytes and Terabytes.

PROF. FIROZKHAN S PATHAN JAMIA POLYTEHCNIC, AKKALKUWA 6


PYTHON PROGRAMMING (314004) SOLVED LAB MANUAL

6. Write a program to swap the value of two variables.

7. Write a program to calculate surface volume and area of a cylinder.

PROF. FIROZKHAN S PATHAN JAMIA POLYTEHCNIC, AKKALKUWA 7


PYTHON PROGRAMMING (314004) SOLVED LAB MANUAL

Practical No. 4: Write simple Python program to demonstrate use of conditional


statements: if’ statement, ‘if … else’ statement, Nested ‘if’ statement.
1. Differentiate between if-else and nested-if statement about different Logical operators in
Python with appropriate examples.
In Python, if-else and nested-if statements are used for conditional execution of code blocks.
if-else: A simple conditional structure where one block of code is executed if a condition is true,
and another block is executed if the condition is false.
Syntax :
if condition:
# Code to execute if the condition is true
else:
# Code to execute if the condition is false
Example :
x = 10
y=5
if x > 5 and y < 10:
print("Both conditions are true")
else:
print("At least one condition is false")
Nested-if: A more complex conditional structure where an if-else statement is placed inside
another if or else block. This allows for testing multiple conditions in a hierarchical manner.
Syntax :
if condition1:
# Code to execute if condition1 is true
if condition2:
# Code to execute if both condition1 and condition2 are true
else:
# Code to execute if condition1 is true but condition2 is false
else:
# Code to execute if condition1 is false
x = 10
y=5
if x > 5:
if y < 10:
print("x is greater than 5 and y is less than 10")
else:
print("x is greater than 5 but y is not less than 10")
else:
print("x is not greater than 5")
If else, elif in Python 🐍 | Nested If | Python for Beginners
https://www.youtube.com/watch?v=9xiFcK3MRYA&list=PLxCzCOWd7aiEb4apyN1Y8mD-QuUTr3SPQ&index=28

PROF. FIROZKHAN S PATHAN JAMIA POLYTEHCNIC, AKKALKUWA 8


PYTHON PROGRAMMING (314004) SOLVED LAB MANUAL

2. Write a program to check the largest number among the three numbers

3. Write a program to check if the input year is a leap year of not.

4. List operators used in if conditional statement.


In Python, you can use various operators within an if conditional statement:
Comparison Operators:
• ==: Equal to
• !=: Not equal to
• <: Less than
• >: Greater than
• <=: Less than or equal to
• >=: Greater than or equal to
Logical Operators:
• and: Returns True if both conditions are true
• or: Returns True if at least one condition is true
• not: Inverts the result of the condition

PROF. FIROZKHAN S PATHAN JAMIA POLYTEHCNIC, AKKALKUWA 9


PYTHON PROGRAMMING (314004) SOLVED LAB MANUAL

Membership Operators:
• in: Returns True if a value is found in a sequence (e.g., list, tuple, string)
• not in: Returns True if a value is not found in a sequence
Identity Operators:
• is: Returns True if two variables refer to the same object
• is not: Returns True if two variables do not refer to the same object

5. Write a program to check if a Number is Positive, Negative or Zero.

6. Write a program that takes the marks of 5 subjects and displays the grades.

For more examples visit : https://www.programiz.com/python-programming/examples

PROF. FIROZKHAN S PATHAN JAMIA POLYTEHCNIC, AKKALKUWA 10


PYTHON PROGRAMMING (314004) SOLVED LAB MANUAL

Practical No. 5: Write Python program to demonstrate use of looping


statements: ‘while’ loop, ‘for’ loop and Nested loop

1. Write a Python program that takes a number and checks whether it is a palindrome or not.

2. Write a Python program to print all even numbers between 1 to 100 using while loop.

PROF. FIROZKHAN S PATHAN JAMIA POLYTEHCNIC, AKKALKUWA 11


PYTHON PROGRAMMING (314004) SOLVED LAB MANUAL

3. Print the following patterns using loop:


a. b.
1010101 *
10101 ***
101 *****
1 ***
*

PROF. FIROZKHAN S PATHAN JAMIA POLYTEHCNIC, AKKALKUWA 12


PYTHON PROGRAMMING (314004) SOLVED LAB MANUAL

4. Change the following Python code from using a while loop to for loop:
x=1
while x<10:
print x
x+=1

PROF. FIROZKHAN S PATHAN JAMIA POLYTEHCNIC, AKKALKUWA 13


PYTHON PROGRAMMING (314004) SOLVED LAB MANUAL

5. Write a Python Program to Reverse a given number.

6. Write a python program to find Factorial of given number.

7. Find sum of four-digit number.

PROF. FIROZKHAN S PATHAN JAMIA POLYTEHCNIC, AKKALKUWA 14


PYTHON PROGRAMMING (314004) SOLVED LAB MANUAL

8. Write a python program to find Fibonacci series for given number.

PROF. FIROZKHAN S PATHAN JAMIA POLYTEHCNIC, AKKALKUWA 15


PYTHON PROGRAMMING (314004) SOLVED LAB MANUAL

Practical No. 6: Write Python program to demonstrate use of loop control


statements: continue, pass, break

1. Describe Keyword "continue" with example.


In Python, the continue keyword is used within loops (like for and while) to skip the remaining
code in the current iteration and move on to the next iteration.
Syntax :
while condition:
# code block
if some_condition:
continue
# more code block

2. Describe pass with example.


Pass statement in Python is a null operation or a placeholder. It is used when a statement is
syntactically required but we don’t want to execute any code. It does nothing but allows us to
maintain the structure of our program.
Syntax :
Pass
Acts as a placeholder.
It does nothing, allowing you to create an empty block of code without causing errors.

def my_empty_function():
pass # Placeholder for future implementation
my_empty_function()

3. Write program to demonstrate use of break.


The break statement in Python is used to exit or “break” out of a loop (either a for or while
loop) prematurely. When the break statement is executed, the program immediately exits the
loop, and the control moves to the next line of code after the loop.

PROF. FIROZKHAN S PATHAN JAMIA POLYTEHCNIC, AKKALKUWA 16


PYTHON PROGRAMMING (314004) SOLVED LAB MANUAL

4. Write program to demonstrate use of nested if-else.

PROF. FIROZKHAN S PATHAN JAMIA POLYTEHCNIC, AKKALKUWA 17


PYTHON PROGRAMMING (314004) SOLVED LAB MANUAL

Practical No. 7: Write Python program to perform following operations on Lists:


Create list, Access list, Update list (Add item, Remove item), and Delete list
A list is a type of data structure that holds an ordered collection of items, which means you can
store anything from integers to strings, to other lists, and so on. They are mutable, allowing you
to change their content without changing their identity.

1. Write syntax for a method to sort a list.


The syntax for sorting a list in Python using the sort() method is as follows:
Syntax : list_name.sort(key=None, reverse=False)
Example :
my_list = [5, 2, 9, 1, 5, 6]
sorted_list = sort_list(my_list)
print(sorted_list) # Output: [1, 2, 5, 5, 6, 9]
• list_name: This is the name of the list that needs to be sorted.
• key: An optional argument that specifies a function to be called on each list element prior to
making comparisons.

PROF. FIROZKHAN S PATHAN JAMIA POLYTEHCNIC, AKKALKUWA 18


PYTHON PROGRAMMING (314004) SOLVED LAB MANUAL

• reverse: An optional argument. If set to True, the list is sorted in descending order. By
default, it is False, which sorts the list in ascending order.

2. Justify the statement “Lists are mutable” not.


A list is considered "mutable" because it can be changed or modified after it is created, meaning
you can add, remove, or update individual elements within the list without needing to create a
new list entirely
Key points supporting the statement "Lists are mutable":
• Direct element modification
• Adding and removing elements
• In-place changes
Example :
my_list = [1, 2, 3]
# Change an element
my_list[1] = 5
print(my_list) # Output: [1, 5, 3]
# Add an element
my_list.append(4)
print(my_list) # Output: [1, 5, 3, 4]
# Remove an element
my_list.remove(3)
print(my_list) # Output: [1, 5, 4]

3. Describe various list functions.


Here's a description of various list functions in Python:
• append(element): Adds an element to the end of the list.
• extend(iterable): Appends elements from an iterable (like another list, tuple, or string) to
the end of the list.
• insert(index, element): Inserts an element at a specific index in the list.
• remove(element): Removes the first occurrence of an element from the list.
• pop(index): Removes and returns the element at a specific index
• clear(): Removes all elements from the list, making it empty.
• index(element): Returns the index of the first occurrence of an element.
• count(element): Returns the number of times an element appears in the list.
• sort(): Sorts the elements of the list in ascending order (can be modified to sort in
descending order).
• reverse(): Reverses the order of elements in the list.
• copy(): Returns a shallow copy of the list.
• len(list): Returns the number of elements in the list.
• sorted(list): Returns a new sorted list from the elements of the original list without
modifying the original list.
• min(list): Returns the smallest element in the list.
• max(list): Returns the largest element in the list.
• sum(list): Returns the sum of all elements in the list (only works for numerical lists).

PROF. FIROZKHAN S PATHAN JAMIA POLYTEHCNIC, AKKALKUWA 19


PYTHON PROGRAMMING (314004) SOLVED LAB MANUAL

Example :
my_list = [3, 1, 4, 1, 5, 9]
# Using core functions
print(len(my_list)) # Output: 6
print(sorted(my_list)) # Output: [1, 1, 3, 4, 5, 9]
print(min(my_list)) # Output: 1
print(max(my_list)) # Output: 9
# Using list methods
my_list.append(2)
print(my_list) # Output: [3, 1, 4, 1, 5, 9, 2]
my_list.insert(2, 7)
print(my_list) # Output: [3, 1, 7, 4, 1, 5, 9, 2]
my_list.remove(1) # Removes the first occurrence of 1
print(my_list) # Output: [3, 7, 4, 1, 5, 9, 2]
my_list.sort()
print(my_list) # Output: [1, 2, 3, 4, 5, 7, 9]
my_list.reverse()
print(my_list) # Output: [9, 7, 5, 4, 3, 2, 1]

4. Describe the use pop operator in list.


The pop() operator in Python lists removes an element from a specified position and returns it. If
no index is specified, it removes and returns the last element of the list. The pop() method
modifies the list in place.
Example :
my_list = [10, 20, 30, 40, 50]
# Remove and return the element at index 2
popped_element = my_list.pop(2)
print(f"Popped element: {popped_element}")# Popped element: 30
print(f"Updated list: {my_list}") # Updated list: [10, 20, 40, 50]
# Remove and return the last element
popped_element = my_list.pop()
print(f"Popped element: {popped_element}")# Popped element: 50
print(f"Updated list: {my_list}") # Updated list: [10, 20, 40]

6. Write a Python program to find common items from two lists.

The & operator or intersection() method is the most efficient way to find common elements
between two lists.

PROF. FIROZKHAN S PATHAN JAMIA POLYTEHCNIC, AKKALKUWA 20


PYTHON PROGRAMMING (314004) SOLVED LAB MANUAL

7. Write a Python program to reverse a list.

PROF. FIROZKHAN S PATHAN JAMIA POLYTEHCNIC, AKKALKUWA 21


PYTHON PROGRAMMING (314004) SOLVED LAB MANUAL

Practical No. 9: Write python program to perform following operations on tuple:


Create, Access, Print, Delete & Convert tuple into list and vice-versa
A tuple is a sequence of immutable Python objects. Tuples are sequences, just like lists. The
differences between tuples and lists are, the tuples cannot be changed unlike lists and tuples use
parentheses, whereas lists use square brackets.

1. Define empty tuple. Write syntax to create empty tuple.


An empty tuple is a tuple that contains no elements. It is represented by an empty set of
parentheses. Empty tuples are useful as placeholders
empty_tuple = ()
or
empty_tuple = tuple() # Creating an empty tuple using the tuple() constructor

PROF. FIROZKHAN S PATHAN JAMIA POLYTEHCNIC, AKKALKUWA 22


PYTHON PROGRAMMING (314004) SOLVED LAB MANUAL

2. Write syntax to copy specific elements existing tuple into new tuple.
original_tuple = (10, 20, 30, 40, 50)
indices_to_copy = [0, 2, 4]
new_tuple = tuple(original_tuple[i] for i in indices_to_copy)
print(new_tuple) # Output: (10, 30, 50)
Note :
new_tuple = tuple(original tuple[i] for i in indices_to_copy):
• This is the core of the code. It's a list comprehension:
o for i in indices_to_copy: Iterates through each index in the indices_to_copy list.
o original_tuple[i]: Accesses the element at the current index i within the original_tuple.
• The resulting list of selected elements is then converted into a tuple using the tuple()
constructor.

3. Compare tuple with list (Any 4 points).


Feature List Tuple
Mutability Mutable (changeable) Immutable (unchangeable)
Syntax [item1, item2, item3] (item1, item2, item3)
Use Cases Collections that require Collections that should remain constant
modification
Performance Slightly slower, more memory Slightly faster, less memory overhead
overhead
Methods More built-in methods for Fewer built-in methods due to
manipulation immutability

4. Create a tuple and find the minimum and maximum number from it.

PROF. FIROZKHAN S PATHAN JAMIA POLYTEHCNIC, AKKALKUWA 23


PYTHON PROGRAMMING (314004) SOLVED LAB MANUAL

5. Write a Python program to find the repeated items of a tuple.

6. Print the number in words for Example: 1234 => One Two Three Four

PROF. FIROZKHAN S PATHAN JAMIA POLYTEHCNIC, AKKALKUWA 24


PYTHON PROGRAMMING (314004) SOLVED LAB MANUAL

Practical No. 10: Write python program to perform following operations on the
Set: Create set, Access Set, Update Set, Delete Set
A set is an unordered collection of items. Every element is unique (no duplicates) and must be
immutable (which cannot be changed). A set is created by placing all the items (elements) inside
curly braces {}, separated by comma or by using the built-in function set(). It can have any number
of items and they may be of different types (integer, float, tuple, string etc.).

1. Describe the various set operations.


Here is a description of the set operations available in Python:
• Union: Combines elements from two sets, removing duplicates. It can be performed using
the | operator or the union() method.
set1 = {1, 2, 3}
set2 = {3, 4, 5}
union_set = set1 | set2 # or set1.union(set2)
# union_set will be {1, 2, 3, 4, 5}

PROF. FIROZKHAN S PATHAN JAMIA POLYTEHCNIC, AKKALKUWA 25


PYTHON PROGRAMMING (314004) SOLVED LAB MANUAL

• Intersection: Returns common elements present in both sets. It can be performed using
the & operator or the intersection() method.
set1 = {1, 2, 3}
set2 = {3, 4, 5}
intersection_set = set1 & set2 # or set1.intersection(set2)
# intersection_set will be {3}
• Difference: Returns elements present in the first set but not in the second set. It can be
performed using the - operator or the difference() method.
set1 = {1, 2, 3}
set2 = {3, 4, 5}
difference_set = set1 - set2 # or set1.difference(set2)
# difference_set will be {1, 2}
• Symmetric Difference: Returns elements present in either the first set or the second set, but
not in both. It can be performed using the ^ operator or the symmetric_difference() method.
set1 = {1, 2, 3}
set2 = {3, 4, 5}
symmetric_difference_set = set1 ^ set2
# symmetric_difference_set will be {1, 2, 4, 5}
• isdisjoint(): Checks if two sets have no elements in common. Returns True if they are
disjoint, False otherwise.
set1 = {1, 2, 3}
set2 = {4, 5, 6}
disjoint_check = set1.isdisjoint(set2)
# disjoint_check will be True
These set operations offer efficient ways to manipulate and analyze data stored in sets, leveraging
their inherent properties of uniqueness and unordered nature.

2. Describe the various methods of set.


• add(element): Adds a single element to the set. If the element already exists, it has no effect.
my_set = {1, 2, 3}
my_set.add(4)
print(my_set) # Output: {1, 2, 3, 4}
• update(iterable): Adds multiple elements from an iterable (like a list, tuple, or another set)
to the set.
my_set = {1, 2, 3}
my_set.update([4, 5], {6, 7})
print(my_set) # Output: {1, 2, 3, 4, 5, 6, 7}
• remove(element): Removes a specific element from the set. Raises a KeyError if the element
is not found.
my_set = {1, 2, 3, 4}
my_set.remove(2)
print(my_set) # Output: {1, 3, 4}
• discard(element): Removes a specific element from the set. If the element is not found, it
does nothing.
my_set = {1, 2, 3, 4}

PROF. FIROZKHAN S PATHAN JAMIA POLYTEHCNIC, AKKALKUWA 26


PYTHON PROGRAMMING (314004) SOLVED LAB MANUAL

my_set.discard(5) # No error raised


print(my_set) # Output: {1, 2, 3, 4}
• pop(): Removes and returns an arbitrary element from the set.
my_set = {1, 2, 3}
removed_element = my_set.pop()
print(my_set) # Output: {1, 2} or {2, 3} (order is not guaranteed)
print(removed_element)
• clear(): Removes all elements from the set.
my_set = {1, 2, 3}
my_set.clear()
print(my_set) # Output: set()
• union(other_set): Returns a new set containing all elements from both sets.
set1 = {1, 2, 3}
set2 = {3, 4, 5}
union_set = set1.union(set2)
print(union_set) # Output: {1, 2, 3, 4, 5}
• intersection(other_set): 1 Returns a new set containing only the elements
set1 = {1, 2, 3}
set2 = {3, 4, 5}
intersection_set = set1.intersection(set2)
print(intersection_set) # Output: {3}
• difference(other_set): Returns a new set containing elements in the first set but not in the
second.
set1 = {1, 2, 3}
set2 = {3, 4, 5}
difference_set = set1.difference(set2)
print(difference_set) # Output: {1, 2}
• symmetric_difference(other_set): Returns a new set containing elements in either set, but
not in both.
set1 = {1, 2, 3}
set2 = {3, 4, 5}
symmetric_difference_set = set1.symmetric_difference(set2)
print(symmetric_difference_set) # Output: {1, 2, 4, 5}
• issubset(other_set): Checks if the set is a subset of another set.
set1 = {1, 2}
set2 = {1, 2, 3}
print(set1.issubset(set2)) # Output: True
• issuperset(other_set): Checks if the set is a superset of another set.
set1 = {1, 2, 3}
set2 = {1, 2}
print(set1.issuperset(set2)) # Output: True
• isdisjoint(other_set): Checks if the set has no elements in common with another set.
set1 = {1, 2}
set2 = {3, 4}
print(set1.isdisjoint(set2)) # Output: True

PROF. FIROZKHAN S PATHAN JAMIA POLYTEHCNIC, AKKALKUWA 27


PYTHON PROGRAMMING (314004) SOLVED LAB MANUAL

3. Write a Python program to create a set, add member(s) in a set and remove one item
from set.

4. Write a Python program to find maximum and the minimum value in a set.

5. Write a Python program to find the length of a set.

PROF. FIROZKHAN S PATHAN JAMIA POLYTEHCNIC, AKKALKUWA 28


PYTHON PROGRAMMING (314004) SOLVED LAB MANUAL

Practical No. 11: Write python program to perform following functions on Set:
Union, Intersection, Difference, Symmetric Difference

1. Explain mutable and immutable data structures.


Mutable data structures allow modification of their contents after they are created. Common
mutable data structures in Python include:
• Lists: Ordered collections of items, allowing addition, removal, and modification of
elements.
• Dictionaries: Collections of key-value pairs, where values can be modified, added, or
removed.
• Sets: Unordered collections of unique elements, allowing addition and removal of items.
Immutable data structures, do not allow modification after creation. Any operation that appears
to modify an immutable data structure actually creates a new object with the modified
value. Common immutable data structures in Python include:
• Strings: Sequences of characters that cannot be changed after creation.
• Tuples: Ordered collections of items, similar to lists, but immutable.
• Numeric types (int, float, bool): Represent numerical values and boolean values that
cannot be changed.
Mutability affects how data structures are handled in memory and how they behave when
passed as arguments to functions or assigned to new variables. Mutable objects can be modified
in place, affecting all references to that object, while immutable objects, when "modified," result
in a new object, leaving the original unchanged.

2. Explain any six set function with example.


Explain in above Practical

3. Write a Python program to perform following operations on set: intersection of sets


Explain in above Practical

4. union of sets, set difference, symmetric difference, clear a set.


Explain in above Practical

5. Difference between set & tuple


Feature Set Tuple
Mutability Mutable Immutable
(items can be added or removed) (items cannot be changed after creation)
Ordering Unordered Ordered
(items have no specific position) (items maintain their position)
Duplicates No duplicates allowed Duplicates allowed
Syntax Enclosed in curly braces {} Enclosed in parentheses ()

PROF. FIROZKHAN S PATHAN JAMIA POLYTEHCNIC, AKKALKUWA 29


PYTHON PROGRAMMING (314004) SOLVED LAB MANUAL

Practical No. 12: Write python program to perform following operations on the
Dictionary: Create, Access, Update, Delete, Looping through Dictionary, Create
Dictionary from list
Python dictionary is a container of key-value pairs. It is mutable and can contain mixed types. A
dictionary is an unordered collection. Python dictionaries are called associative arrays or hash
tables in other languages. The keys in a dictionary must be immutable objects like strings or
numbers. They must also be unique within a dictionary.

PROF. FIROZKHAN S PATHAN JAMIA POLYTEHCNIC, AKKALKUWA 30


PYTHON PROGRAMMING (314004) SOLVED LAB MANUAL

1. Write a Python script to sort (ascending and descending) a dictionary by value.

https://sparkbyexamples.com/python/how-to-sort-dictionary-by-value-in-python/
2. Write a Python script to concatenate following dictionaries to create a new one.
Sample Dictionary: dic1 = {1:10, 2:20} dic2 = {3:30, 4:40} dic3 = {5:50,6:60}

PROF. FIROZKHAN S PATHAN JAMIA POLYTEHCNIC, AKKALKUWA 31


PYTHON PROGRAMMING (314004) SOLVED LAB MANUAL

https://www.w3resource.com/python-exercises/dictionary/python-data-type-dictionary-
exercise-19.php

3. Write a Python program to perform following operations on set: intersection of sets, union
of sets, set difference, symmetric difference, clear a set.
See in SET practical

4. Write a Python program to combine two dictionary adding values for common keys.
d1 = {'a': 100, 'b': 200, 'c':300}
d2 = {'a': 300, 'b': 200, 'd':400}

6. Write a Python program to find the highest 3 values in a dictionary.

PROF. FIROZKHAN S PATHAN JAMIA POLYTEHCNIC, AKKALKUWA 32


PYTHON PROGRAMMING (314004) SOLVED LAB MANUAL

OR : Write a Python program to find the Largest of 3 values in a dictionary.

6. What is the output of the following program?


dictionary1 = {'Google' : 1, 'Facebook' : 2, 'Microsoft' : 3}
dictionary2 = {'GFG' : 1, 'Microsoft' : 2, 'Youtube' : 3 }
dictionary1.update(dictionary2)
for key, values in dictionary1.items(): print(key, values)
Output :

PROF. FIROZKHAN S PATHAN JAMIA POLYTEHCNIC, AKKALKUWA 33


PYTHON PROGRAMMING (314004) SOLVED LAB MANUAL

Practical No. 13: Write a user define function to implement following features:
Function without argument, Function with argument, Function returning value
Functions are the most important aspect of an application. A function can be defined as the
organized block of reusable code which can be called whenever required.

1. Write a Python function that takes a number as a parameter and check the number is prime
or not. For more practice : https://www.w3resource.com/python-exercises/

PROF. FIROZKHAN S PATHAN JAMIA POLYTEHCNIC, AKKALKUWA 34


PYTHON PROGRAMMING (314004) SOLVED LAB MANUAL

2. What is the output of the following program?


def myfunc(text, num):
while num > 0:
print(text)
num = num - 1
myfunc('Hello', 4)

3. Write a Python function to calculate the factorial of a number (a non-negative integer). The
function accepts the number as an argument.

4. Write a Python function that accepts a string and calculate the number of upper case letters
and lower case letters.

PROF. FIROZKHAN S PATHAN JAMIA POLYTEHCNIC, AKKALKUWA 35


PYTHON PROGRAMMING (314004) SOLVED LAB MANUAL

5. What is the output of the following program?


num = 1
def func():
num = 3
print(num)
func()
print(num)

PROF. FIROZKHAN S PATHAN JAMIA POLYTEHCNIC, AKKALKUWA 36


PYTHON PROGRAMMING (314004) SOLVED LAB MANUAL

Practical No. 14: Write a user define function to implement for following problem:
Function positional/required argument, Function with keyword argument,
Function with default argument, Function with variable length argument

Function with Positional/Required Arguments


Positional arguments are those that must be passed in the correct position when calling the
function.
def greet(name, age):
print(f"Hello {name}, you are {age} years old.")
# Calling the function
greet("Aziz", 25)
O/p: Hello Aziz, you are 25 years old
Function with Keyword Arguments
Keyword arguments are those where you specify the argument by name, rather than position.
This can make the code clearer.
def greet(name, age):
print(f"Hello {name}, you are {age} years old.")
# Calling the function using keyword arguments
greet(age=30, name="Asif")
O/p: Hello Asif, you are 30 years old.
Function with Default Arguments
Default arguments are values that the function uses if no value is provided for them when the
function is called.
def greet(name, age=30):
print(f"Hello {name}, you are {age} years old.")
# Calling the function with one argument
greet("Afzal ") # age will default to 30
# Calling the function with both arguments
greet("Khan ", 40)
O/p: Hello Afzal, you are 30 years old.
Hello Khan, you are 40 years old
Function with Variable Length Arguments
A function can accept a variable number of arguments using *args for positional arguments and
**kwargs for keyword arguments.
# Function with variable-length positional arguments (*args)
def sum_numbers(*args):
total = sum(args)
print(f"The sum is: {total}")
# Calling the function with different number of arguments
sum_numbers(1, 2, 3)
sum_numbers(4, 5, 6, 7, 8)
# Function with variable-length keyword arguments (**kwargs)
def display_info(**kwargs):
for key, value in kwargs.items():
print(f"{key}: {value}")

PROF. FIROZKHAN S PATHAN JAMIA POLYTEHCNIC, AKKALKUWA 37


PYTHON PROGRAMMING (314004) SOLVED LAB MANUAL

# Calling the function with different keyword arguments


display_info(name="Akmal", age=22, city="New York")
O/p: The sum is: 6
The sum is: 30
name: Akmal
age: 22
city: New York

1. What are positional arguments?


Positional arguments in Python are the arguments that are passed to a function in a specific order.
The values are assigned to parameters based on their position in the function call. The first
argument is assigned to the first parameter, the second argument to the second parameter, and
so on.

2. Write program to demonstrate use of variable length arguments.

PROF. FIROZKHAN S PATHAN JAMIA POLYTEHCNIC, AKKALKUWA 38


PYTHON PROGRAMMING (314004) SOLVED LAB MANUAL

3. What is a Function Argument in Python?


In Python, a function argument is a value you pass into a function when you call it. These values
are assigned to parameters in the function and are used inside the function.
Types:
• Positional Arguments: Passed in a specific order.
• Keyword Arguments: Passed with the argument name, order doesn't matter.
• Default Arguments: Parameters with a default value, used if no value is provided.
• Variable-Length Arguments: Allow you to pass a variable number of arguments using *args
(for positional) or **kwargs (for keyword).

4. Explain function with keyword argument.


A function with keyword arguments in Python allows you to pass arguments to a function by
explicitly specifying the parameter names. This means the order of the arguments doesn't matter,
as long as you provide the correct name for each argument.
def greet(name, age):
print(f"Hello {name}, you are {age} years old.")
greet(age=30, name="Sameer")
O/p: Hello Sameer, you are 30 years old.

5. What will be the output of following code?


def print_animals(*animals):
for animal in animals:
print(animal)
print_animals("Lion", "Elephant", "Wolf", "Gorilla")

6. What will be the output of following code


def print_food(**foods):
for food in foods.items():
print(food)
print_food(Lion="Carnivore", Elephant="Herbivore", Gorilla="Omnivore")

PROF. FIROZKHAN S PATHAN JAMIA POLYTEHCNIC, AKKALKUWA 39


PYTHON PROGRAMMING (314004) SOLVED LAB MANUAL

Practical No. 15: Write Python program to demonstrate use of following


advanced functions: lambda, map, reduce
Python is a dynamic yet straightforward typed language, and it provides multiple libraries and
inbuilt functions. There are different methods to perform the same task and in Python lambda
function proves to be king of all, which can be used everywhere in different ways.
• lambda is use to perform a quick operation (e.g., square each number).
• map is use to apply this operation to each element in the list.
• reduce is use to calculate the sum of all squared numbers.

1. What does the filter() function in Python do?


The filter() function in Python is used to filter elements from an iterable (like a list or a tuple)
based on a condition specified by a function. It returns an iterator that contains only the elements
for which the function returns True.
Syntax : filter(function, iterable)
# List of numbers
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]
# Use filter() to get only even numbers
even_numbers = list(filter(lambda x: x % 2 == 0, numbers))
# Print the result
print(even_numbers)
O/p: [2, 4, 6, 8]

2. What is the purpose of the map() function in Python?


The map() function in Python applies a given function to all items in an iterable (like a list) and
returns a map object (an iterator) that yields the results. It's useful when you want to perform a
transformation or operation on each element of an iterable without using an explicit loop.
Syntax : map(function, iterable)

PROF. FIROZKHAN S PATHAN JAMIA POLYTEHCNIC, AKKALKUWA 40


PYTHON PROGRAMMING (314004) SOLVED LAB MANUAL

# Function to square a number


def square(x):
return x * x
numbers = [1, 2, 3, 4]
# Using map() to square each number
squared_numbers = map(square, numbers)
# Convert the map object to a list to view the results
print(list(squared_numbers))
O/p: [1, 4, 9, 16]

3. What will be the output of following code?


from functools import reduce
def multiply(x, y):
return x * y

numbers = [1, 2, 3, 4, 5]
result = reduce(multiply, numbers)
print(result)

4. What will be the output of following code


numbers = [1, 2, 3, 4, 5]
squared = map(lambda x: x**2,numbers)
print(list(squared))

5. What will be the output of following code?


def even_check(num):
if num % 2 == 0:
return True
else:
return False
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
even_numbers = filter(even_check, numbers)
print(list(even_numbers))

PROF. FIROZKHAN S PATHAN JAMIA POLYTEHCNIC, AKKALKUWA 41

You might also like