0% found this document useful (0 votes)
22 views8 pages

Python Programming Lab Exercises Guide

Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
22 views8 pages

Python Programming Lab Exercises Guide

Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

L T P C

Programming in Python - Lab

Version 1.0 0 0 1 1
Pre-requisites/Exposure Basic principles of programming language
Co-requisites

COURSE OUTLINE

[Link] Lab Exercise Contents

1. Lab. Exercise 1 Python Installation and starting with python

2. Lab. Exercise 2 Input statements, operators

3. Lab. Exercise 3 Conditional Statements: if, elif and nested if statements

4. Lab. Exercise 4 Loops: for and while, nested loops

5. Lab. Exercise 5 String and set

6. Lab. Exercise 6 Dictionary, Tuple, Lists

7. Lab. Exercise 7
Functions, lambda function, recursion

8. Lab. Exercise 8
File handling and Exception Handling

9. Lab. Exercise 9
Object Oriented Programming
10 Lab Exercise 10 Numpy, Pandas and Matplotlib

Practical No 1: Python Installation and starting with python


Q1. Install Python and understand difference between scripting and interactive modes in IDLE.
Q2. Write Python programs to print strings in the given manner:
a) Hello Everyone !!!
b) Hello
World
c) Hello
World
d) ‘ Rohit’ s date of birth is 12\05\1999’
Q3) Declare a string variable called x and assign it the value “Hello”.
Print out the value of x
Q4) Take different data types and print values using print function.
Q5) Take two variable a and b. Assign your first name and last name. Print your Name after adding
your First name and Last name together.
Q6) Declare three variables, consisting of your first name, your last name and Nickname. Write
a program that prints out your first name, then your nickname in parenthesis and then your last
name.
Example output : George ( woody ) Washington.
Q7) Declare and assign values to suitable variables and print in the following way :
NAME : NIKUNJ BANSAL
ROLL NO : 500069944
DATE OF BIRTH : 13 Oct 1999
ADDRESS : Galgotias University
Greater Noida
Pincode : 123456
Programme : AI & ML
Semester : 2

Practical no 2: Use of input statements, operators

1. Declare these variables (x, y and z) as integers. Assign a value of 9 to x, Assign a value of
7 to y, perform addition, multiplication, division and subtraction on these two variables
and Print out the result.
2. Write a Program where the radius is taken as input to compute the area of a circle.
3. Write a Python program to solve (x+y)*(x+y)
Test data : x = 4 , y = 3
Expected output: 49
4. Write a program to compute the length of the hypotenuse (c) of a right triangle using
Pythagoras theorem.
5. Write a program to find simple interest.
6. Write a program to find area of triangle when length of sides are given.
7. Write a program to convert given seconds into hours, minutes and remaining seconds.
8. Write a program to swap two numbers without taking additional variable.
9. Write a program to find sum of first n natural numbers.
10. Write a program to print truth table for bitwise operators( & , | and ^ operators)
11. Write a program to find left shift and right shift values of a given number.
12. Using membership operator find whether a given number is in sequence (10,20,56,78,89)
13. Using membership operator find whether a given character is in a string.

Practical No 3 : Conditional Statements


1. Check whether given number is divisible by 3 and 5 both.
2. Check whether a given number is multiple of five or not.
3. Find the greatest among two numbers. If numbers are equal than print “numbers are
equal”.
4. Find the greatest among three numbers assuming no two values are same.
5. Check whether the quadratic equation has real roots or imaginary roots. Display the roots.
6. Find whether a given year is a leap year or not.
7. Write a program which takes any date as input and display next date of the calendar
e.g.
I/P: day=20 month=9 year=2005
O/P: day=21 month=9 year 2005
8. Print the grade sheet of a student for the given range of cgpa. Scan marks of five subjects
and calculate the percentage.
CGPA=percentage/10
CGPA range:
0 to 3.4 -> F
3.5 to 5.0->C+
5.1 to 6->B
6.1 to 7-> B+
7.1 to 8-> A
8.1 to 9->A+
9.1 to 10-> O (Outstanding)

Sample Gradesheet
Name: Rohit Sharma
Roll Number: R17234512 ROLL NO: 50005673
Sem: 1 Course: [Link]. CSE AI&ML

Subject name: Marks


PDS: 70
Python: 80
Chemistry: 90
English: 60
Physics: 50
Percentage: 70%
CGPA:7.0
Grade: A
Practical No 4: Loops

Q1) Find a factorial of given number.


Q2) Find whether the given number is Armstrong number.
Q3) Print Fibonacci series up to given term.
Q4) Write a program to find if given number is prime number or not.
Q5) Check whether given number is palindrome or not.
Q6) Write a program to print sum of digits.
Q7) Count and print all numbers divisible by 5 or 7 between 1 to 100.
Q8) Convert all lower cases to upper case in a string.
Q9) Print all prime numbers between 1 and 100.
Q10) Print the table for a given number:
5*1=5
5 * 2 = 10………..

Practical No 5: String and Sets

1. Write a program to count and display the number of capital letters in a given string.
2. Count total number of vowels in a given string.
3. Input a sentence and print words in separate lines.
4. WAP to enter a string and a substring. You have to print the number of times that the
substring occurs in the given string. String traversal will take place from left to right, not
from right to left.
Sample Input
ABCDCDC
CDC
Sample Output
2
5. Given a string containing both upper and lower case alphabets. Write a Python program to
count the number of occurrences of each alphabet (case insensitive) and display the same.
Sample Input
ABaBCbGc
Sample Output
2A
3B
2C
1G
6. Program to count number of unique words in a given sentence using sets.
7. Create 2 sets s1 and s2 of n fruits each by taking input from user and find:
a) Fruits which are in both sets s1 and s2
b) Fruits only in s1 but not in s2
c) Count of all fruits from s1 and s2
8. Take two sets and apply various set operations on them :
S1 = {Red ,yellow, orange , blue }
S2 = {violet, blue , purple}
Practical No 6: Lists, tuples, dictionary

1. Scan n values in range 0-3 and print the number of times each value has occurred.
2. Create a tuple to store n numeric values and find average of all values.
3. WAP to input a list of scores for N students in a list data type. Find the score of the runner-up
and print the output.
Sample Input
N=5
Scores= 2 3 6 6 5
Sample output
5
Note: Given list is [2, 3, 6, 6, 5]. The maximum score is 6, second maximum is 5. Hence, we
print 5 as the runner-up score.
4. Create a dictionary of n persons where key is name and value is city.
a) Display all names
b) Display all city names
c) Display student name and city of all students.
d) Count number of students in each city.
5. Store details of n movies in a dictionary by taking input from the user. Each movie must store
details like name, year, director name, production cost, collection made (earning) & perform
the following :-
a) print all movie details
b) display name of movies released before 2015
c) print movies that made a profit.
d) print movies directed by a particular director.

Practical no 7: Functions

1. Write a Python function to find the maximum and minimum numbers from a sequence of
numbers. (Note: Do not use built-in functions.)
2. Write a Python function that takes a positive integer and returns the sum of the cube of all
the positive integers smaller than the specified number.
3. Write a Python function to print 1 to n using recursion. (Note: Do not use loop)
4. Write a lambda function which gives tuple of max and min from a list.
Sample input: [10, 6, 8, 90, 12, 56]
Sample output: (90,6)
5. Write functions to explain mentioned concepts:
a. Keyword argument
b. Default argument
c. Variable length argument

Practical no 8: File Handling and Exception Handling


1. Add few names, one name in each row, in “[Link] file”.
a. Count no of names
b. Count all names starting with vowel
c. Find longest name
2. Store integers in a file.
a. Find the max number
b. Find average of all numbers
c. Count number of numbers greater than 100
3. Assume a file [Link] with details of 5 cities in given format (cityname population(in lakhs)
area(in sq KM) ):
Example:
Dehradun 5.78 308.20
Delhi 190 1484
……………
Open file [Link] and read to:
a. Display details of all cities
b. Display city names with population more than 10Lakhs
c. Display sum of areas of all cities
4. Input two values from user where the first line contains N, the number of test cases. The
next N lines contain the space separated values of a and b. Perform integer division and
print a/b. Handle exception in case of ZeroDivisionError or ValueError.
Sample input
10
2$
31
Sample Output :
Error Code: integer division or modulo by zero
Error Code: invalid literal for int() with base 10: '$' 3
5. Create multiple suitable exceptions for a file handling program.

Practical No 9: Classes and objects


Q1. Create a class of student (name, sap id, marks[phy,chem,maths] ). Create 3 objects by taking
inputs from the user and display details of all students.
Q2. Add constructor in the above class to initialize student details of n students and implement
following methods:
a) Display() student details
b) Find Marks_percentage() of each student
c) Display result() [Note: if marks in each subject >40% than Pass else Fail]
Write a Function to find average of the class.
Q3. Create programs to implement different types of inheritances.
Q4. Create a class to implement method Overriding.
Q5. Create a class for operator overloading which adds two Point Objects where Point has x & y
values
e.g. if
P1(x=10,y=20)
P2(x=12,y=15)
P3=P1+P2 => P3(x=22,y=35)

Practical No 10: Data Analysis and Visualization

Q1. Create numpy array to find sum of all elements in an array.


Q2. Create numpy array of (3,3) dimension. Now find sum of all rows & columns individually.
Also find 2nd maximum element in the array.
Q3. Perform Matrix multiplication of any 2 n*n matrices.
Q4 Write a Pandas program to get the powers of an array values element-wise.
Note: First array elements raised to powers from second array
Sample data: {'X':[78,85,96,80,86], 'Y':[84,94,89,83,86],'Z':[86,97,96,72,83]}
Expected Output:
XYZ
0 78 84 86
1 85 94 97
2 96 89 96
3 80 83 72
4 86 86 83

Q5. Write a Pandas program to get the first 3 rows of a given DataFrame.
Sample Python dictionary data and list labels:
exam_data = {'name': ['Anastasia', 'Dima', 'Katherine', 'James', 'Emily', 'Michael', 'Matthew',
'Laura', 'Kevin', 'Jonas'],
'score': [12.5, 9, 16.5, [Link], 9, 20, 14.5, [Link], 8, 19],
'attempts': [1, 3, 2, 3, 2, 3, 1, 1, 2, 1],
'qualify': ['yes', 'no', 'yes', 'no', 'no', 'yes', 'yes', 'no', 'no', 'yes']}
labels = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']
Expected Output:
First three rows of the data frame:
attempts name qualify score
a 1 Anastasia yes 12.5
b 3 Dima no 9.0
c 2 Katherine yes 16.5
Q6. Write a Pandas program to find and replace the missing values in a given DataFrame which
do not have any valuable information.
Q7. Create a program to demonstrate different visual forms using Matplotlib.

Common questions

Powered by AI

File handling and exception handling in Python intersect significantly, as managing files dynamically involves numerous potential errors that must be anticipated and handled gracefully. File operations such as opening, reading, writing, and closing can fail due to reasons like missing files, permission errors, or unsupported operations. Integrating exception handling ensures these scenarios do not lead to program crashes by allowing developers to implement error-catching mechanisms using 'try', 'except', and 'finally' blocks . This intersection is vital in real-world applications where robustness and reliability are crucial, as users can encounter myriad environments and errors that need to be managed to maintain seamless application performance.

Functions and lambda expressions in Python serve different purposes that impact performance and readability. Regular functions come with a name and the ability to consist of multiple statements, making them useful for complex operations requiring readability and maintenance through documentation and structured code blocks . Lambda expressions, or anonymous functions, are compact and typically used for single-line operations, such as simple operations or function arguments in higher-order functions. While lambda functions can make code concise, they may reduce readability if overused or applied in complex scenarios, potentially harming comprehension due to the lack of a function name and support for documentation.

Recursion in Python involves a function calling itself to solve problems by breaking them down into smaller, more manageable sub-problems. This method is particularly effective for problems characterized by repetitive structures where solutions depend on solutions to smaller instances of the same problem. Examples include computing factorials, traversing data structures like trees, and implementing algorithms such as the Tower of Hanoi or quicksort . When applied effectively, recursion can express solutions in an elegant and concise manner, though care should be taken to ensure base cases are defined to avoid infinite loops and stack overflows.

Lists, tuples, and dictionaries in Python each have distinct characteristics that impact data handling. Lists are mutable sequences, which means their content can be changed—they are ideal for working with dynamic collections of items. Tuples, however, are immutable, providing a performance benefit since their fixed state allows for optimized operations but limits modification. This makes tuples suitable for read-only data. Dictionaries are unordered collections that store data in key-value pairs, allowing for fast access to values using keys . These structural differences influence how data is manipulated, accessed, and altered, making each type best suited for different use cases depending on the need for mutability, speed of access, and method of data organization.

Numpy, pandas, and matplotlib serve complementary roles in data analysis and visualization in Python. Numpy provides essential support for large, multi-dimensional arrays and matrices along with a collection of mathematical functions to operate on these arrays efficiently. Pandas offer data manipulation and analysis tools, especially useful for handling structured data through dataframes, enabling complex data operations and transformation . Matplotlib is employed for data visualization, allowing data plotted in a wide array of graph formats to reveal insights through visual analysis. Together, numpy and pandas prepare and process the data by performing transformations, which matplotlib can then use to visualize these datasets, enabling a coherent data analysis pipeline that interacts seamlessly between computation and graphical representation.

Object-oriented programming (OOP) in Python offers several benefits for managing complex data structures and application logic, such as encapsulation, inheritance, and polymorphism. These principles help in organizing code into modular, reusable objects, which enhances maintainability and scalability. Encapsulation allows data hiding and abstraction, ensuring that implementation details remain hidden while providing clear interfaces . Inheritance promotes code reuse by enabling new classes to derive properties and behaviors from existing classes, reducing redundancy. Polymorphism allows methods to operate on objects of different classes, enhancing flexibility. However, potential challenges include the complexity of designing OOP systems appropriately, leading to issues like over-engineering and increased difficulty in debugging and understanding highly abstracted systems.

Implementing error handling mechanisms in Python involves several challenges, such as identifying the correct exceptions to catch without overloading the code with unnecessary checks, and ensuring that exception handling does not obscure actual code errors or logical issues. The complexity increases when attempting to anticipate rare or unexpected errors that occur in diverse environments . Despite these challenges, error handling significantly enhances program reliability by preventing crashes and allowing graceful recovery from errors. By capturing exceptions with try-except blocks and including finally clauses for clean-up operations, programs can maintain a stable state and provide informative feedback to users or logs, thereby improving overall user experience and system resilience.

Different types of function arguments in Python, such as keyword, default, and variable length, have significant implications for improving flexibility and usability in a program. Keyword arguments allow functions to be called with parameters in any order, enhancing clarity and readability. Default arguments enable functions to be called with fewer arguments than defined by providing preset values, which simplifies function calls and reduces errors . Variable-length arguments, using *args and **kwargs, allow functions to accept an arbitrary number of positional or keyword arguments, respectively, thereby offering maximum flexibility in handling unforeseen use cases and dynamic needs. Together, these functionalities enhance the adaptability of functions to diverse scenarios and datasets.

Loops in Python, such as 'for' and 'while' loops, are pivotal in handling repetitive tasks efficiently by reducing redundancy and automating the execution of iterative operations. They allow a block of code to be executed repeatedly, which can be essential for tasks like processing items in a list, generating a sequence of numbers, or simulating repetitive processes over large datasets . These loops, when combined with conditionals and suitable logic, can significantly reduce time complexity and improve performance by minimizing manual intervention and leveraging automated iteration.

Conditional statements like 'if', 'elif', and 'else' allow programs to execute specific sections of code based on defined conditions, effectively enabling decision-making capabilities within software applications. They are used to create branching logic where different outcomes can occur depending on the input or environment, enhancing the ability for software to handle complex scenarios . For example, they can validate inputs, authenticate users, or manage application workflows, making them invaluable for building dynamic and responsive software solutions. Effective use involves clearly defined conditions and comprehensive coverage of potential cases to ensure robustness and adaptability.

You might also like