0% found this document useful (0 votes)
8 views20 pages

Python Programming Exercises Overview

The document lists various Python programming exercises, each focusing on different concepts such as user-defined modules, conditional statements, loops, file handling, exception handling, and data analysis with and without Pandas. Each program includes a brief description, code examples, and sample outputs demonstrating the functionality. The exercises are designed to enhance understanding of Python programming and its applications.
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)
8 views20 pages

Python Programming Exercises Overview

The document lists various Python programming exercises, each focusing on different concepts such as user-defined modules, conditional statements, loops, file handling, exception handling, and data analysis with and without Pandas. Each program includes a brief description, code examples, and sample outputs demonstrating the functionality. The exercises are designed to enhance understanding of Python programming and its applications.
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

LIST OF PROGRAMS

Program Course
Problem Statement
# Outcome
Building Python Modules + Obtaining User Data + Printing Desired
Output
1 File 1: greetings_module.py (user-defined module) CO1

2 Conditional if, Nested if, else and elif Based program CO4

.Iteration (loops) using Different Data Structures

3 Strings, Lists, Tuples, Sets, Dictionary CO4

User-defined Modules + Standard Library (random, math, sys, string,


4 etc.) CO4

5 Program based on Input–Output (File Handling) CO4

6 Program based on Exception Handling CO4

7 Program based on Simple Data Analysis (without Pandas) CO4

8 Program based on Pandas CO4


1. Building Python Modules + Obtaining User Data + Printing Desired Output
File 1: greetings_module.py (user-defined module)
# greetings_module.py
# --------------------
# A simple user-defined module that contains functions
# to greet the user and calculate his/her age.

from datetime import datetime

def get_age(year_of_birth: int) -> int:


"""Return current age of the user."""
current_year = [Link]().year
return current_year - year_of_birth

def make_greeting(name: str, age: int) -> str:


"""Return a formatted greeting message."""
return f"Hello {name}, you are {age} years old. Have a great day!"
File 2: use_greetings.py (main program)
# use_greetings.py
# ----------------
# Program to show:
# 1. Using a Python module (greetings_module)
# 2. Obtaining user data (input)
# 3. Printing desired output (formatted message)

import greetings_module # importing our own module

# ----- obtaining user data from keyboard -----


name = input("Enter your name: ")
year = int(input("Enter your birth year (e.g., 2003): "))

# ----- processing using functions from module -----


age = greetings_module.get_age(year)
message = greetings_module.make_greeting(name, age)

# ----- printing desired output -----


print("\n----- RESULT -----")
print(message)
Sample Run / Output
Enter your name: Rahul
Enter your birth year (e.g., 2003): 2004

----- RESULT -----


Hello Rahul, you are 21 years old. Have a great day!
2. Conditional if, Nested if, else and elif
Program: grading_if_elif.py
# Program to demonstrate:
# 1. Simple if
# 2. Nested if
# 3. if - elif - else ladder

marks = int(input("Enter marks out of 100: "))

# Simple if
if marks >= 0 and marks <= 100:
print("Valid marks entered.")

# Nested if (inside outer if)


if marks >= 90:
grade = "A+"
elif marks >= 80:
grade = "A"
elif marks >= 70:
grade = "B"
elif marks >= 60:
grade = "C"
elif marks >= 50:
grade = "D"
else:
grade = "F"

print(f"Your grade is: {grade}")


else:
print("Invalid marks! Marks must be between 0 and 100.")
Sample Output
Enter marks out of 100: 76
Valid marks entered.
Your grade is: B
3. Iteration (loops) using Different Data Structures
Strings, Lists, Tuples, Sets, Dictionary
Program: loops_and_collections.py
# Program to demonstrate iteration (for loop, while loop)
# over different data structures: string, list, tuple, set, dictionary

# ---------- 1. String ----------


name = "Python"

print("Characters in string:")
for ch in name: # iterating over each character
print(ch, end=" ")
print("\nLength of string using while loop:")
i=0
while i < len(name):
print(name[i], end=" ")
i += 1

print("\n" + "-"*40)

# ---------- 2. List ----------


numbers = [10, 20, 30, 40, 50]
print("List elements and their squares:")
for n in numbers:
print(n, "->", n*n)

print("-"*40)

# ---------- 3. Tuple ----------


fruits = ("apple", "banana", "mango")
print("Tuple elements:")
for f in fruits:
print(f)

print("-"*40)

# ---------- 4. Set ----------


unique_numbers = {2, 4, 6, 8, 2, 4}
print("Set elements (no duplicates):")
for u in unique_numbers:
print(u)

print("-"*40)

# ---------- 5. Dictionary ----------


student = {"name": "Anita", "age": 20, "course": "BCA"}
print("Dictionary keys and values:")
for key, value in [Link]():
print(key, ":", value)
Sample Output (shortened)
Characters in string:
Python
Length of string using while loop:
Python
----------------------------------------
List elements and their squares:
10 -> 100
20 -> 400
...
----------------------------------------
Tuple elements:
apple
banana
mango
----------------------------------------
Set elements (no duplicates):
2
4
6
8
----------------------------------------
Dictionary keys and values:
name : Anita
age : 20
course : BCA
4. User-defined Modules + Standard Library (random, math, sys, string, etc.)
File 1: stats_module.py
# stats_module.py
# User-defined module for basic statistics

def mean(numbers):
"""Return average of a list of numbers."""
return sum(numbers) / len(numbers)

def maximum(numbers):
"""Return maximum value from a list."""
return max(numbers)
File 2: use_standard_library.py
# use_standard_library.py
# Program that uses:
# - user-defined module (stats_module)
# - standard library modules: random, math, sys, string
# - optional: numpy & scipy (if installed)

import random
import math
import sys
import string
import stats_module

# Optional imports (will not crash if not installed)


try:
import numpy as np
from scipy import stats
except ImportError:
np = None
stats = None

# ----- using sys module -----


print("Command line arguments are:", [Link])

# ----- generate random numbers -----


random_numbers = [[Link](1, 100) for _ in range(5)]
print("Random numbers:", random_numbers)

# ----- use our stats_module -----


print("Mean =", stats_module.mean(random_numbers))
print("Max =", stats_module.maximum(random_numbers))

# ----- use math module -----


x = 16
print(f"Square root of {x} is", [Link](x))

# ----- use string module -----


print("All lowercase letters:", string.ascii_lowercase)

# ----- optional: numpy and scipy -----


if np is not None and stats is not None:
arr = [Link](random_numbers)
print("NumPy array:", arr)
print("Mean using NumPy:", [Link]())
else:
print("NumPy/Scipy not installed, skipping their demo.")
Sample Output (example)
Command line arguments are: ['use_standard_library.py']
Random numbers: [42, 7, 89, 23, 55]
Mean = 43.2
Max = 89
Square root of 16 is 4.0
All lowercase letters: abcdefghijklmnopqrstuvwxyz
NumPy/Scipy not installed, skipping their demo.
5. Program based on Input–Output (File Handling)
Program: file_io_example.py
# Program to demonstrate file input and output
# It reads lines from '[Link]' and writes only
# the lines having more than 10 characters into '[Link]'

input_file = "[Link]"
output_file = "[Link]"

# ----- writing some sample data to input file -----


with open(input_file, "w") as f:
[Link]("Hi\n")
[Link]("Python is fun\n")
[Link]("BCA Lab\n")
[Link]("File handling in Python\n")

# ----- reading from input file and writing filtered lines -----
with open(input_file, "r") as fin, open(output_file, "w") as fout:
for line in fin:
if len([Link]()) > 10: # simple condition
[Link](line)

print("Data copied from [Link] to [Link] (only long lines).")


Sample Output
Data copied from [Link] to [Link] (only long lines).
Content of [Link]:
Python is fun
File handling in Python
6. Program based on Exception Handling
Program: exception_example.py
# Program to show exception handling using try-except-else-finally

try:
a = int(input("Enter numerator: "))
b = int(input("Enter denominator: "))

result = a / b # may raise ZeroDivisionError


except ValueError:
print("Error: Please enter only integers.")
except ZeroDivisionError:
print("Error: Denominator cannot be zero.")
else:
# executes only if no exception occurs
print("Division successful. Result =", result)
finally:
# always executes
print("Thank you for using this program.")
Sample Output 1 (no error)
Enter numerator: 10
Enter denominator: 2
Division successful. Result = 5.0
Thank you for using this program.
Sample Output 2 (division by zero)
Enter numerator: 10
Enter denominator: 0
Error: Denominator cannot be zero.
Thank you for using this program.
7. Program based on Simple Data Analysis (without Pandas)
Program: simple_data_analysis.py
# Simple data analysis on marks of students using core Python

marks = [78, 56, 90, 66, 84, 72, 95, 40]

print("Marks:", marks)

# Total, average, highest, lowest


total = sum(marks)
avg = total / len(marks)
highest = max(marks)
lowest = min(marks)

print("Total marks =", total)


print("Average marks =", round(avg, 2))
print("Highest marks =", highest)
print("Lowest marks =", lowest)

# Count how many students passed (>= 50)


passed = [m for m in marks if m >= 50]
print("Number of students passed =", len(passed))
Sample Output
Marks: [78, 56, 90, 66, 84, 72, 95, 40]
Total marks = 581
Average marks = 72.62
Highest marks = 95
Lowest marks = 40
Number of students passed = 7
8. Program based on Pandas
Program: pandas_example.py
# Program to demonstrate basic use of Pandas library
# It creates a DataFrame of students and their marks
# and performs simple analysis.

import pandas as pd

# ----- create a small data set -----


data = {
"Name": ["Amit", "Bhavna", "Chetan", "Divya"],
"Marks": [78, 92, 67, 85],
"City": ["Gorakhpur", "Lucknow", "Kanpur", "Varanasi"]
}

df = [Link](data)

print("Full DataFrame:")
print(df)

# ----- basic analysis -----


print("\nBasic statistics of Marks:")
print(df["Marks"].describe()) # count, mean, min, max etc.
print("\nStudents scoring more than 80:")
print(df[df["Marks"] > 80])
Sample Output
Full DataFrame:
Name Marks City
0 Amit 78 Gorakhpur
1 Bhavna 92 Lucknow
2 Chetan 67 Kanpur
3 Divya 85 Varanasi
Basic statistics of Marks:
count 4.000000
mean 80.500000
std 10.022472
min 67.000000
25% 74.250000
50% 81.500000
75% 87.750000
max 92.000000
Name: Marks, dtype: float64
Students scoring more than 80:
Name Marks City
1 Bhavna 92 Lucknow
3 Divya 85 Varanasi

Common questions

Powered by AI

The use of modules in Python contributes to code modularity and organization by encapsulating related functions and classes into separate files or packages. User-defined modules like 'greetings_module' allow developers to organize code logically according to functionality, thus enhancing readability and maintainability. Standard libraries offer prepackaged solutions for common tasks, reducing the need to code from scratch and promote code reuse. This modular design enables easier debugging and updating, as changes in one module do not necessarily affect others. Overall, it encourages a cleaner, more maintainable codebase .

Performing data analysis with core Python offers simplicity and minimal setup, using built-in functions for tasks like calculating totals, averages, and filtering data, as demonstrated by the program analyzing student marks. However, it can be less efficient and more cumbersome for complex data manipulations and large datasets. Libraries like Pandas, on the other hand, provide advanced data structures and functions optimized for data manipulation and analysis, such as DataFrames for handling large datasets efficiently and methods for comprehensive statistical analysis. While Pandas requires additional installation and learning curve, it significantly enhances productivity and capability in data analysis tasks beyond what core Python can achieve .

User-defined modules, like the 'greetings_module' in Python, improve maintainability by encapsulating functions into separate files that can be easily reused across different programs without rewriting code. This modular approach allows for separation of concerns, as each module can focus on a specific part of the functionality, thereby making the programs easier to manage and update. For example, the 'greetings_module' contains functions for greeting users and calculating age, which can be imported and used in any program that requires this functionality. Moreover, it supports reusability since once a module is created, it can be shared and reused in multiple applications, reducing redundancy and potential errors in the code .

Using loops with data structures such as strings, lists, and dictionaries allows for efficient processing and manipulation of data. Loops enable iteration over each element of these data structures, making it possible to apply operations or transformations to each element. For example, iterating over a list allows squaring each number, as shown with the list where each number is printed alongside its square. Similarly, a dictionary can be looped over to access both keys and values, facilitating complex data manipulations and accommodating dynamic data changes efficiently .

Exception handling in Python is characterized by its clear syntax and structured flow, using try-except-else-finally blocks. Unlike languages like C that use error codes or C++ which uses both exceptions and error codes, Python offers a unified and readable approach with a built-in hierarchy of exceptions. This allows precise handling of various error conditions with minimal boilerplate code. Additionally, Python's finally block guarantees execution of clean-up code, which can be complex in languages like C/C++, where programmers must manually ensure it. This makes Python's approach more straightforward and less error-prone for developers .

Python's conditional statements such as if, nested if, and elif provide a structured approach for decision-making by evaluating specific conditions and executing corresponding actions. This control flow enables complex logic to be easily implemented and read. For instance, in a grading program, these conditions allow the program to assign grades based on a range of marks entered by the user. The program first checks if the marks are within a valid range, then uses a nested if structure to assign the appropriate grade ('A+' for marks >= 90, 'B' for 70-79, etc.) using if, elif, and else, demonstrating how conditions guide the program flow to produce the desired output .

The integration of standard libraries such as random, math, and sys expands Python's functionality by providing specialized tools without the need for external packages. The random library enables generation of random numbers for simulations and random sampling, math provides mathematical functions and constants for complex calculations, and sys offers tools to interact with the interpreter, such as retrieving command-line arguments. These libraries are crucial for extending Python's capabilities, allowing developers to accomplish a wide range of tasks efficiently, as seen in the program that uses these libraries for statistical calculations and command-line interactions .

Exception handling mechanisms like try-except-else-finally enhance the robustness of Python programs by allowing them to gracefully handle errors and exceptions that occur during execution. The try block contains code that might throw an exception, while the except block provides code to handle specific exceptions like ValueError or ZeroDivisionError, preventing the program from crashing abruptly. The else block is executed if no exceptions occur, and the finally block is executed regardless of whether an exception is thrown, ensuring essential clean-up actions are performed. This structured approach ensures that programs can manage unexpected situations effectively and maintain a smooth user experience .

File handling in Python can be used to process and filter data by reading input from files, performing operations based on specific conditions, and writing the results to output files. For instance, a program can read each line of an 'input.txt' file and write only the lines that exceed a certain length to 'output.txt'. This is achieved using the open function in read ('r') and write ('w') modes. The program iterates over each line, applies the condition of a length greater than 10 characters, and selectively writes these lines to the output file, demonstrating the ability to filter and transform data effectively within files .

Iterative processing in Python allows for efficient access and manipulation of different data structures like strings, lists, tuples, sets, and dictionaries. Each structure has its characteristics and use cases: strings and lists allow indexing, making them suited for ordered data, while sets provide fast membership tests and are unordered, ideal for eliminating duplicates. Dictionaries offer key-value pair management, allowing efficient searches and storage of associative data. Python's for and while loops iterate effectively over these structures, facilitating operations like transformations and searches across diverse datasets, which are crucial for applications requiring dynamic data handling .

You might also like