0% found this document useful (0 votes)
2 views18 pages

Python UNIT 2

The document outlines a syllabus for a Python course covering sequences, mapping types, file I/O, and practical applications in civil engineering. It includes descriptive and objective questions, assignment tasks, MOOC resources, real-time applications, minor project ideas, and unit tests. The focus is on utilizing Python for data management and analysis in engineering contexts.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views18 pages

Python UNIT 2

The document outlines a syllabus for a Python course covering sequences, mapping types, file I/O, and practical applications in civil engineering. It includes descriptive and objective questions, assignment tasks, MOOC resources, real-time applications, minor project ideas, and unit tests. The focus is on utilizing Python for data management and analysis in engineering contexts.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 18

PYTHON

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

2. Which of the following is a valid way to concatenate two tuples?


a) tuple1 + tuple2
b) tuple1.append(tuple2)
c) tuple1.extend(tuple2)
d) tuple1 * tuple2
Answer: a) tuple1 + tuple2

3. What is the output of 'Civil' * 3?


a) 'Civil3'
b) 'CivilCivilCivil'
c) 'Civil*3'
d) 'C i v i l C i v i l C i v i l'
Answer: b) 'CivilCivilCivil'

4. Which method can be used to remove the last item of a list?


a) remove()
b) delete()
c) pop()
d) clear()
Answer: c) pop()

5. Which of the following is not a valid list operation?


a) Slicing
b) Indexing
c) Multiplication
d) Sorting tuples
Answer: d) Sorting tuples

6. What is the output of len((1, 2, (3, 4)))?


a) 2
b) 3
c) 4
d) Error
Answer: b) 3

7. Which of the following is a valid way to create a list?


a) [1, 2, 3]
b) (1, 2, 3)
c) {1, 2, 3}
d) list[1, 2, 3]
Answer: a) [1, 2, 3]

8. What does the split() method do to a string?


a) Combines two strings
b) Splits the string into a list based on a delimiter
c) Converts the string to uppercase
d) Finds a substring within the string
Answer: b) Splits the string into a list based on a delimiter

9. Which of the following statements about tuples is true?


a) Tuples consume more memory than lists
b) Tuples are slower to access compared to lists
c) Tuples are hashable and can be used as dictionary keys
d) Tuples can only store integers
Answer: c) Tuples are hashable and can be used as dictionary keys

10. What will be the output of the following code? list(range(5))


a) [1, 2, 3, 4, 5]
b) [0, 1, 2, 3, 4]
c) [5, 4, 3, 2, 1]
d) [0, 1, 2, 3, 4, 5]
Answer: b) [0, 1, 2, 3, 4]

11. Which data structure is used to store key-value pairs in Python?


a) Set
b) Dictionary
c) List
d) Tuple
Answer: b) Dictionary

12. What will be the output of {1, 2, 3} & {2, 3, 4}?


a) {1, 2, 3, 4}
b) {2, 3}
c) {1}
d) Error
Answer: b) {2, 3}

13. Which method is used to add a key-value pair to a dictionary?


a) append()
b) add()
c) update()
d) insert()
Answer: c) update()
14. What will be the output of the code set('engineering')?
a) {e, n, g, i, r}
b) {'e', 'n', 'g', 'i', 'r'}
c) {'engineering'}
d) {'n', 'g', 'e', 'i', 'r'}
Answer: b) {'e', 'n', 'g', 'i', 'r'}

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

17. Which method removes all items from a set?


a) clear()
b) delete()
c) remove_all()
d) discard()
Answer: a) clear()

18. What will be the output of {1, 2, 3} | {3, 4, 5}?


a) {3}
b) {1, 2, 3, 4, 5}
c) {1, 2, 4, 5}
d) {}
Answer: b) {1, 2, 3, 4, 5}

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+'

20. Which method is used to read the entire contents of a file?


a) readline()
b) read()
c) readlines()
d) fetch()
Answer: b) read()

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.

MOOCS course or NPTEL courses

1. Programming, Data Structures and Algorithms Using Python

https://onlinecourses.nptel.ac.in/noc24_cs45/preview

2. Python for Data Science

https://onlinecourses.nptel.ac.in/noc22_cs32/preview

3. The Joy of Computing using Python

https://onlinecourses.nptel.ac.in/noc24_cs57/preview

4. Programming in Python

https://onlinecourses.swayam2.ac.in/cec22_cs20/preview

5. NOC: Programming, Data Structures and Algorithms in Python

https://archive.nptel.ac.in/courses/106/106/106106145
REAL TIME APPLICATION

1. Construction Site - Lists and Tuples

 Scene: A construction site with a crane, workers, and various equipment.


 Python Application:
o Lists: Used to store and process data such as loads applied on beams, column
dimensions, or material quantities.
o Tuples: Used to represent fixed values like coordinates of structural joints or
dimensions of pre-fabricated components.
o Example:

python

CopyEdit

loads = [10, 20, 15, 25] # in tons

avg_load = sum(loads) / len(loads)

print(f"Average Load: {avg_load} tons")

2. Traffic Monitoring System - Dictionaries

 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

print(f"Total vehicles: {sum(traffic_data.values())}")

3. Surveyor with GPS Device - Sets

 Scene: A surveyor using a GPS device to collect land survey data.


 Python Application:
o Sets: Used to eliminate duplicate survey points or coordinate readings.
o Example:

python

CopyEdit

survey_points = {(10, 20), (15, 25), (10, 20), (20, 30)}

unique_points = set(survey_points)

print(f"Unique survey points: {unique_points}")

4. Material Properties - File I/O

 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

with open('material_data.txt', 'w') as file:

file.write("Steel: Density=7850 kg/m³, Yield Strength=250 MPa\n")


with open('material_data.txt', 'r') as file:

print(file.read())

Key Features in the Image:

 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.

Minor Project Ideas:

1. Traffic Data Analysis and Visualization

Objective: Develop a Python program to collect, analyze, and visualize traffic data for a

specific road or intersection.

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.

2. Material Properties Management System

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

Answer any two questions

All questions carry equal marks MAX MARKS: 10

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

Answer any two questions

All questions carry equal marks MAX MARKS: 10

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

1. Strings and Lists:

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.

2. Lists and Tuples:

Write a function that accepts a list of numbers and returns a tuple containing the smallest and
largest number from the list.

3. Dictionaries and Sets:

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.

5. File Reading and Writing:

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.

6. Sequences and Built-in Functions:

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.

9. Files and Persistent Storage:


Write a Python program that uses the pickle module to serialize and deserialize a Python
dictionary containing student information (name, roll number, marks). Store the serialized
data in a file and retrieve it from the file.

10. Advanced File Operations:

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.

Solved tutorial questions

1. Strings and Lists:

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

elif char in consonants:

consonant_count += 1

return vowel_count, consonant_count

# Test
input_str = input("Enter a string: ")

vowels, consonants = count_vowels_consonants(input_str)

print(f"Vowels: {vowels}, Consonants: {consonants}")

2. Lists and Tuples:

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):

return (min(numbers), max(numbers))

# Test

num_list = [12, 5, 7, 34, 2, 45]

result = find_min_max(num_list)

print(f"Smallest number: {result[0]}, Largest number: {result[1]}")

3. Dictionaries and Sets:

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

def create_dict(keys, values):

return dict(zip(keys, values))


def key_exists(d, key):

return key in d

def remove_key(d, key):

if key in d:

del d[key]

# Test

keys = ['name', 'age', 'city']

values = ['Alice', 25, 'New York']

my_dict = create_dict(keys, values)

print(f"Dictionary: {my_dict}")

print(f"Does 'age' exist? {key_exists(my_dict, 'age')}")

remove_key(my_dict, 'age')

print(f"Dictionary after removing 'age': {my_dict}")

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:

with open(filename, 'r') as file:

words = chars = 0

for line in file:

words += len(line.split())

chars += len(line)

return words, chars

except FileNotFoundError:

return "File not found."

# Test

filename = input("Enter the filename: ")

result = count_words_and_chars(filename)

if isinstance(result, tuple):

print(f"Words: {result[0]}, Characters: {result[1]}")

else:

print(result)

5. File Reading and Writing:

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

def extract_names(input_file, output_file):

try:

with open(input_file, 'r') as csv_file:

reader = csv.reader(csv_file)

names = [row[0] for row in reader if row] # Assuming names are in the first column

with open(output_file, 'w') as txt_file:

for name in names:

txt_file.write(name + "\n")

print("Names extracted successfully.")

except FileNotFoundError:

print(f"{input_file} not found.")

except Exception as e:

print(f"An error occurred: {e}")

# Test

extract_names('people.csv', 'names.txt')

6. Sequences and Built-in Functions:

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 = list(set(nums)) # Remove duplicates

unique_nums.sort()

return unique_nums[-2] if len(unique_nums) > 1 else None

# Test

nums = [12, 35, 1, 10, 34, 1]

print(f"The second largest number is: {second_largest(nums)}")

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

def set_operations(list1, list2):

set1 = set(list1)

set2 = set(list2)

union = set1 | set2

intersection = set1 & set2

difference = set1 - set2

return union, intersection, difference

# Test

list1 = [1, 2, 3, 4]
list2 = [3, 4, 5, 6]

union, intersection, difference = set_operations(list1, list2)

print(f"Union: {union}, Intersection: {intersection}, Difference: {difference}")

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

def calculate(operation, num1, num2):

if operation == 'add':

return num1 + num2

elif operation == 'subtract':

return num1 - num2

elif operation == 'multiply':

return num1 * num2

elif operation == 'divide':

return num1 / num2

else:

return "Invalid operation"

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])

result = calculate(operation, num1, num2)

print(f"Result: {result}")

You might also like