Python UNIT 2
Python UNIT 2
UNIT 2
SYLLABUS
Sequences: Strings, Lists, and Tuples- Built-in Functions, Special features.
Mapping and Set Types: Dictionaries, Sets- Built-in Functions.
Files and Input / Output: File Objects, File Built-in Functions, File Built-in Methods, File
Built-in Attributes, Standard Files, Command-line Arguments, File System, File Execution,
Persistent Storage Modules, Related Modules.
10 DESCRIPTIVE QUESTIONS
S.No Question BL CO
1 Explain how Python lists and tuples can be used to store and process data 2 CO-2
related to structural analysis, such as material properties, forces, and
displacements. Provide an example program to calculate the average of a
given dataset.
2 Describe how strings in Python can be manipulated to process and analyze 3 CO-2
survey data from text files. Write a program to extract specific information
like coordinates or elevations.
3 Discuss the differences between mutable and immutable sequences (lists, 3 CO-2
tuples) in Python and their relevance when dealing with large datasets in
civil engineering.
4 Write a Python program to sort a list of soil test results based on parameters 2 CO-2
such as density or moisture content. Explain the role of built-in functions
used in the program.
5 How can tuples be used to represent the nodes and elements in a finite 2 CO-2
element mesh for structural analysis? Illustrate with a Python example.
6 Explain how Python dictionaries can be used to store and query material 2 CO-2
properties like strength, density, and elasticity. Write a program to retrieve
material data for a given key.
7 Describe how Python sets can be used to manage and eliminate duplicate 5 CO-2
survey points or coordinates from a dataset. Provide an example program.
8 Explain the process of reading and writing civil engineering data to files using 4 CO-2
Python. Write a program to read data from a file and calculate the total
weight of construction materials.
9 Discuss how command-line arguments can be used in a Python program to 3 CO-2
execute tasks like batch processing of geotechnical test reports. Write an
example program to demonstrate this.
10 Write a Python program that uses persistent storage (like the shelve 5 CO-2
module) to save and retrieve project data, such as design parameters or
environmental impact results. Explain the benefits of using persistent
storage.
20 objective questions along with answers
1. What is the difference between a list and a tuple in Python?
a) Lists are immutable, tuples are mutable
b) Lists are mutable, tuples are immutable
c) Both are mutable
d) Both are immutable
Answer: b) Lists are mutable, tuples are immutable
15. What happens when you try to access a key that does not exist in a dictionary?
a) Returns None
b) Throws a KeyError
c) Returns an empty string
d) Adds the key with a None value
Answer: b) Throws a KeyError
16. What will the len() function return for the dictionary {1: "A", 2: "B", 3: "C"}?
a) 1
b) 2
c) 3
d) 6
Answer: c) 3
19. What mode should be used to read a file as well as write to it?
a) 'r'
b) 'w'
c) 'rw'
d) 'r+'
Answer: d) 'r+'
ASSIGNMENT QUESTIONS
S.No Question BL CO
1 Write a Python program to count the number of vowels in a given 2 CO-2
string. Use the input: "Civil Engineering is interesting."
2 Create a Python list to store the compressive strengths (in MPa) of 3 CO-2
concrete samples: [30, 32, 28, 35, 31]. Write a program to
calculate the average compressive strength.
3 Create a tuple to represent the coordinates of five survey points: [(10, 6 CO-2
20), (15, 25), (20, 30), (25, 35), (30, 40)]. Write a
program to calculate the distance between the first and last points.
4 Write a Python program to create a dictionary that stores material 4 CO-2
properties of steel, such as density, yield strength, and ultimate
strength. Retrieve and print the value of the yield strength.
5 Write a Python program to read the contents of a file named 6 CO-2
data.txt and count the number of lines in it.
https://onlinecourses.nptel.ac.in/noc24_cs45/preview
https://onlinecourses.nptel.ac.in/noc22_cs32/preview
https://onlinecourses.nptel.ac.in/noc24_cs57/preview
4. Programming in Python
https://onlinecourses.swayam2.ac.in/cec22_cs20/preview
https://archive.nptel.ac.in/courses/106/106/106106145
REAL TIME APPLICATION
python
CopyEdit
Scene: A highway with cars and traffic monitoring equipment, like cameras and
sensors.
Python Application:
o Dictionaries: Used to manage and analyze traffic data, such as vehicle counts,
speeds, and vehicle types.
o Example:
python
CopyEdit
traffic_data = {
"Car": 120,
"Truck": 50,
"Bike": 80
python
CopyEdit
unique_points = set(survey_points)
Scene: A table of material properties such as density, elasticity, and strength stored in
a file for future use.
Python Application:
o File I/O: Used to read and write material property data to files for easy storage
and retrieval.
o Example:
python
CopyEdit
print(file.read())
Labels and Arrows: Clearly connect each real-world scene to its corresponding
Python application.
Soft, Realistic Colors: Help keep the focus on understanding the applications while
maintaining a clean, modern design.
Engineering Context: Relates directly to tasks civil engineers perform daily, such as
analyzing loads, monitoring traffic, surveying land, and managing materials.
Objective: Develop a Python program to collect, analyze, and visualize traffic data for a
Description:
Use dictionaries to store traffic data (e.g., vehicle types, counts, and average speeds).
Utilize lists and tuples to manage time-series data for each hour or day.
Apply Python's file I/O capabilities to store the collected data in a file (e.g., CSV or
JSON).
Generate graphs using libraries like Matplotlib or Seaborn to display trends, such as
peak traffic times or speed variations.
Deliverable: A program that inputs raw traffic data (or uses a dataset), analyzes the
data, and produces visualizations like line charts or bar graphs.
Real-World Relevance: Helps identify traffic patterns and supports decision-making
for traffic management.
Objective: Build a Python-based application to manage and query material properties for
construction projects.
Description:
Create a dictionary to store properties of materials like steel, concrete, and wood
(e.g., density, strength, elasticity).
Use sets to eliminate duplicate material entries or inconsistent data.
Implement file I/O to save and load material properties to/from a file, ensuring
persistent storage.
Add search functionality to retrieve properties for a given material or filter materials
based on specific criteria.
Deliverable: A standalone program or a simple GUI application using Tkinter or
PyQt that can store, retrieve, and update material properties.
Real-World Relevance: Helps streamline material selection and documentation for
structural design or construction projects.
UNIT TEST
SET 1
S.No Question BL CO
1 Explain the difference between a list and a tuple in Python. List and 2 CO-2
explain any two built-in functions that can be used with strings.
2 What is a dictionary in Python? Provide an example and explain how 3 CO-2
you would add a new key-value pair to a dictionary. Also, list any two set
operations that are used to perform mathematical operations.
3 Write a Python program to read the contents of a file and print it to the 2 CO-2
console. What built-in functions are used to open and close a file in
Python?
4 Describe how command-line arguments are passed to a Python 2 CO-2
program. Write a short code snippet that demonstrates reading
command-line arguments in Python.
UNIT TEST
SET 2
S.No Question BL CO
1 How can you modify an element in a list? Provide an example and 2 CO-2
explain how list slicing can be used to extract a portion of a list.
2 What are sets in Python? List any two built-in methods used with sets 3 CO-2
and explain their function with examples.
3 What are the different file modes in Python when opening a file? 2 CO-2
Explain with an example how you would write data to a file.
4 How can you perform file operations in Python using the os module? 2 CO-2
Provide an example of checking if a file exists using the
os.path.exists() function.
10 analytical/programming problems
Write a program that takes a string as input and returns the count of vowels and consonants in
it. Handle both lowercase and uppercase characters.
Write a function that accepts a list of numbers and returns a tuple containing the smallest and
largest number from the list.
Given two lists, one with keys and the other with corresponding values, create a dictionary
using these two lists. Then, write a function to check if a key exists in the dictionary. Also,
demonstrate removing a key from the dictionary.
4. File Input/Output:
Write a Python program that opens a text file, reads its contents line by line, and counts the
number of words and characters in the file. The program should handle file not found
exceptions.
Write a Python program that reads a CSV file, extracts the names of the people from it, and
writes those names to a new text file. Handle errors like missing or malformed CSV files.
Write a program that takes a list of integers and returns the second largest number. You must
use a built-in function and avoid sorting the list.
7. Set Operations:
Write a program that accepts two lists of numbers, converts them to sets, and performs the
following set operations: union, intersection, and difference. Print the results of each
operation.
8. Command-Line Arguments:
Write a Python script that accepts command-line arguments for a mathematical operation
(addition, subtraction, multiplication, division) and two numbers. Perform the specified
operation and print the result.
Write a Python program that monitors a directory for changes (new files, modified files, or
deleted files) and logs these changes in a log file. Use the os and time modules to track file
changes over a period of time.
Question: Write a program that takes a string as input and returns the count of vowels and
consonants in it. Handle both lowercase and uppercase characters.
Solution:
python
Copy
Edit
def count_vowels_consonants(s):
vowels = "aeiouAEIOU"
consonants = "bcdfghjklmnpqrstvwxyzBCDFGHJKLMNPQRSTVWXYZ"
vowel_count = consonant_count = 0
for char in s:
if char in vowels:
vowel_count += 1
consonant_count += 1
# Test
input_str = input("Enter a string: ")
Question: Write a function that accepts a list of numbers and returns a tuple containing the
smallest and largest number from the list.
Solution:
python
Copy
Edit
def find_min_max(numbers):
# Test
result = find_min_max(num_list)
Question: Given two lists, one with keys and the other with corresponding values, create a
dictionary using these two lists. Then, write a function to check if a key exists in the
dictionary. Also, demonstrate removing a key from the dictionary.
Solution:
python
Copy
Edit
return key in d
if key in d:
del d[key]
# Test
print(f"Dictionary: {my_dict}")
remove_key(my_dict, 'age')
4. File Input/Output:
Question: Write a Python program that opens a text file, reads its contents line by line, and
counts the number of words and characters in the file. The program should handle file not
found exceptions.
Solution:
python
Copy
Edit
def count_words_and_chars(filename):
try:
words = chars = 0
words += len(line.split())
chars += len(line)
except FileNotFoundError:
# Test
result = count_words_and_chars(filename)
if isinstance(result, tuple):
else:
print(result)
Question: Write a Python program that reads a CSV file, extracts the names of the people
from it, and writes those names to a new text file. Handle errors like missing or malformed
CSV files.
Solution:
python
Copy
Edit
import csv
try:
reader = csv.reader(csv_file)
names = [row[0] for row in reader if row] # Assuming names are in the first column
txt_file.write(name + "\n")
except FileNotFoundError:
except Exception as e:
# Test
extract_names('people.csv', 'names.txt')
Question: Write a program that takes a list of integers and returns the second largest number.
You must use a built-in function and avoid sorting the list.
Solution:
python
Copy
Edit
def second_largest(nums):
unique_nums.sort()
# Test
7. Set Operations:
Question: Write a program that accepts two lists of numbers, converts them to sets, and
performs the following set operations: union, intersection, and difference. Print the results of
each operation
Solution:
python
Copy
Edit
set1 = set(list1)
set2 = set(list2)
# Test
list1 = [1, 2, 3, 4]
list2 = [3, 4, 5, 6]
8. Command-Line Arguments:
Question: Write a Python script that accepts command-line arguments for a mathematical
operation (addition, subtraction, multiplication, division) and two numbers. Perform the
specified operation and print the result.
Solution:
python
Copy
Edit
import sys
if operation == 'add':
else:
if len(sys.argv) != 4:
print("Usage: python script.py <operation> <num1> <num2>")
else:
operation = sys.argv[1]
num1 = float(sys.argv[2])
num2 = float(sys.argv[3])
print(f"Result: {result}")