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

PythonPracticals

The document outlines practical exercises for a BTech-Civil course at NICMAR University, focusing on Python programming. It includes instructions for installing Python and Visual Studio Code, creating basic programs for construction cost estimation, bridge load capacity checking, cylindrical column volume calculation, beam load analysis, material quantity calculation, and structural load distribution using arrays. Each practical emphasizes key programming concepts such as variables, conditional statements, loops, functions, and data structures.

Uploaded by

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

PythonPracticals

The document outlines practical exercises for a BTech-Civil course at NICMAR University, focusing on Python programming. It includes instructions for installing Python and Visual Studio Code, creating basic programs for construction cost estimation, bridge load capacity checking, cylindrical column volume calculation, beam load analysis, material quantity calculation, and structural load distribution using arrays. Each practical emphasizes key programming concepts such as variables, conditional statements, loops, functions, and data structures.

Uploaded by

Harshil Sachde
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 35

NICMAR University BTech-Civil Introduction to Python [MDC406P]

School of Engineering Batch 1 – Sem IV Practical

Practical 1: Installing Python and setting up the development Environment


Download and Install Python
1. Open a Web Browser (open Google Chrome, Microsoft Edge, or any browser.
2. Type https://www.python.org/downloads/ in the address bar and press Enter.
3. Download Python: Click the yellow Download Python X.X.X button
4. Locate the Downloaded File and open
5. Double-click the downloaded .exe file (e.g., python-3.X.X.exe).
6. Install Python: On the installation screen, check the box Add Python to PATH.
7. Click Install Now.
8. Wait for the installation to finish and click Close.

Verify Python Installation


1. Open Command Prompt
2. Check Python Version: Type python --version and press Enter.
3. If Python is installed correctly, you will see the version number (e.g., Python 3.11.0).

Install Visual Studio Code


1. Download VS Code: Open your browser and go to https://code.visualstudio.com/.
2. Click the blue Download for Windows button.
3. Install VS Code: Locate the downloaded file and double-click it.
4. Follow the setup wizard, checking boxes for Add to PATH and Add Open with Code to
Explorer during installation.
5. Open VS Code: Search for "Visual Studio Code" in the Start Menu and click to open it.

Install Python Extension in VS Code


1. Open Extensions: Click the Extensions icon (on the left toolbar) in VS Code.
2. Search for Python and click Install.
3. Verify Python Extension: Once installed, the Python extension will show options like
syntax highlighting and running Python programs.

Write and Run Your First Python Program


1. Create a Folder: Open File Explorer and create a new folder, e.g., PythonPrograms on
D drive.
2. Create a New File: Open VS Code, click File > Open Folder, and select the
PythonPrograms folder.
3. Click New File (icon at the top) and name it first_program.py.
4. Write Code: Type the following code in the editor

python
print("Hello, World!")

5. Run the Program: Press Ctrl + (to open Terminal in VS Code). Type: python
first_program.py
6. The output Hello, World! will appear in the terminal

Dr. Vijaya Desai (vdesai@nicmar.ac.in)


NICMAR University BTech-Civil Introduction to Python [MDC406P]
School of Engineering Batch 1 – Sem IV Practical

Practical 2: Building a simple construction cost calculator using Python Basic Syntax

Objective: Learn and practice Python's basic syntax by building a simple construction cost
estimator. This practical involves:

1. Using variables to store data.


2. Using input/output functions.
3. Performing basic arithmetic operations.
4. Utilizing conditional statements for decision-making.
5. Displaying the results in a formatted manner.

Task Description: Write a Python program that calculates the total construction cost for a
project based on user inputs for the following:

1. Area of construction (in square meters).


2. Cost per square meter (based on material type).
3. Optional additional costs (e.g., landscaping, electrical work, etc.).

Code Example:

# Step 1: Variables to Store Input Data


print("Welcome to the Construction Cost Estimator")

# Input: Area of construction


area = float(input("Enter the total area to be constructed (in sq. meters): "))

# Input: Material type and cost per square meter


print("\nSelect the type of construction material:")
print("1. Standard - $500 per sq.m")
print("2. Premium - $800 per sq.m")
print("3. Luxury - $1200 per sq.m")

material_choice = int(input("Enter your choice (1, 2, or 3): "))

if material_choice == 1:
cost_per_sq_m = 500
material_type = "Standard"
elif material_choice == 2:
cost_per_sq_m = 800
material_type = "Premium"
elif material_choice == 3:
cost_per_sq_m = 1200
material_type = "Luxury"
else:
print("Invalid choice! Defaulting to Standard material.")
cost_per_sq_m = 500
material_type = "Standard"

# Step 2: Calculate Base Construction Cost


base_cost = area * cost_per_sq_m

Dr. Vijaya Desai (vdesai@nicmar.ac.in)


NICMAR University BTech-Civil Introduction to Python [MDC406P]
School of Engineering Batch 1 – Sem IV Practical

# Step 3: Add Optional Costs


print("\nOptional Add-ons:")
landscaping = input("Do you want landscaping? (yes/no): ").lower() == "yes"
electrical = input("Do you want additional electrical work? (yes/no): ").lower() == "yes"

optional_costs = 0
if landscaping:
optional_costs += 5000 # Fixed cost for landscaping
if electrical:
optional_costs += 7000 # Fixed cost for electrical work

# Step 4: Calculate Total Cost


total_cost = base_cost + optional_costs

# Step 5: Display the Results


print("\n=== Construction Cost Estimate ===")
print(f"Material Type: {material_type}")
print(f"Area: {area} sq.m")
print(f"Cost per sq.m: ${cost_per_sq_m}")
print(f"Base Construction Cost: ${base_cost:.2f}")
if landscaping:
print("Landscaping: $5000")
if electrical:
print("Additional Electrical Work: $7000")
print(f"Total Construction Cost: ${total_cost:.2f}")

Practical 3: Bridge Load Capacity Checker Using If Statements

Objective: Create a Python program that evaluates whether a bridge can handle a given load
based on its maximum load capacity. The program will use if statements to check conditions
and display appropriate messages.

Scenario: The user enters the maximum load capacity of the bridge (in tons) and the total
weight of the vehicles attempting to cross the bridge. The program will:

1. Determine if the load exceeds the bridge's capacity.


2. Display a warning if the load exceeds the limit.
3. Provide suggestions for reducing the load if necessary.

Code Example:

# Step 1: Input - Bridge's maximum load capacity and current load


print("=== Bridge Load Capacity Checker ===")
max_capacity = float(input("Enter the maximum load capacity of the bridge (in tons): "))
current_load = float(input("Enter the total weight of vehicles (in tons): "))

# Step 2: Use if statements to check conditions


if current_load <= max_capacity:

Dr. Vijaya Desai (vdesai@nicmar.ac.in)


NICMAR University BTech-Civil Introduction to Python [MDC406P]
School of Engineering Batch 1 – Sem IV Practical

print("\nThe bridge can safely handle the load.")


else:
print("\nWARNING: The load exceeds the bridge's capacity!")
overload = current_load - max_capacity
print(f"The load exceeds the capacity by {overload:.2f} tons.")

# Step 3: Suggest solutions


if overload <= 5:
print("Suggestion: Remove one or two vehicles to reduce the load.")
elif overload <= 20:
print("Suggestion: Distribute the vehicles into smaller groups.")
else:
print("Suggestion: Do not allow the vehicles to cross until the load is significantly
reduced.")

Key Concepts Practiced:

1. Input/Output: Use input() to get data from the user. Use print() to display messages and
warnings.
2. If Statements: Check whether the load exceeds the bridge's capacity.
3. Nested If Statements: Provide tailored suggestions based on the amount of overload.
4. Arithmetic Operations: Calculate the difference between the load and the capacity.

Practical 4: Calculate Total Volume of Cylindrical Columns Using a Loop

Objective: Write a Python program to calculate the total volume of multiple cylindrical
columns. Use a loop to process data for multiple columns efficiently.

Scenario: In a civil engineering project, multiple cylindrical columns are being constructed.
The user provides the number of columns, along with the radius and height of each
column. The program calculates the total volume of all columns.

Code Example:

import math

# Step 1: Input the number of columns


print("=== Cylindrical Column Volume Calculator ===")
num_columns = int(input("Enter the number of cylindrical columns: "))

# Initialize total volume


total_volume = 0

# Step 2: Loop through each column


for i in range(1, num_columns + 1):
print(f"\nColumn {i}:")
radius = float(input("Enter the radius of the column (in meters): "))
height = float(input("Enter the height of the column (in meters): "))

Dr. Vijaya Desai (vdesai@nicmar.ac.in)


NICMAR University BTech-Civil Introduction to Python [MDC406P]
School of Engineering Batch 1 – Sem IV Practical

# Calculate the volume of the column


volume = math.pi * (radius**2) * height
print(f"Volume of Column {i}: {volume:.2f} cubic meters")

# Add the volume to the total


total_volume += volume

# Step 3: Display the total volume


print(f"\nTotal Volume of {num_columns} Columns: {total_volume:.2f} cubic meters")

Key Concepts Practiced:

1. Loops: Use a for loop to iterate through each column.


2. Input/Output: Take input for each column's radius and height. Display individual and
total volumes.
3. Arithmetic Operations: Calculate the volume of a cylinder using the formula:
Volume=π×radius2×height\text{Volume} = \pi \times \text{radius}^2 \times
\text{height}Volume=π×radius2×height
4. Accumulation: Use a variable (total_volume) to keep a running total.

Practical 5: Beam Load Analysis Using Functions

Objective: Create a Python program that calculates the total load on a beam by defining
reusable functions for input handling, load calculation, and result display. This program
demonstrates the use of functions for modular programming.

Scenario: A beam in a structure supports multiple point loads. The user enters the magnitude
and position of each load. The program calculates the total load and provides the results.

Code Example:

# Function to take load data as input


def get_load_data():
num_loads = int(input("Enter the number of point loads on the beam: "))
loads = [] # List to store (magnitude, position) tuples
for i in range(1, num_loads + 1):
print(f"\nLoad {i}:")
magnitude = float(input("Enter the magnitude of the load (in kN): "))
position = float(input("Enter the position of the load (in meters from the left end): "))
loads.append((magnitude, position))
return loads

# Function to calculate total load


def calculate_total_load(loads):
total_load = sum(load[0] for load in loads) # Sum of all load magnitudes
return total_load

# Function to display load details and total load


def display_results(loads, total_load):

Dr. Vijaya Desai (vdesai@nicmar.ac.in)


NICMAR University BTech-Civil Introduction to Python [MDC406P]
School of Engineering Batch 1 – Sem IV Practical

print("\n=== Beam Load Analysis ===")


print("Loads on the Beam:")
for i, (magnitude, position) in enumerate(loads, start=1):
print(f"Load {i}: Magnitude = {magnitude:.2f} kN, Position = {position:.2f} m")
print(f"\nTotal Load on the Beam: {total_load:.2f} kN")

# Main function to execute the program


def main():
print("=== Beam Load Analysis Program ===")
loads = get_load_data()
total_load = calculate_total_load(loads)
display_results(loads, total_load)

# Run the program


if __name__ == "__main__":
main()

Key Concepts Practiced:

1. Functions: get_load_data: Handles user input for load data. calculate_total_load:


Computes the sum of load magnitudes. display_results: Formats and displays the results.
2. Lists: Use a list of tuples to store load data (magnitude and position).
3. Loops: Iterate through the loads for input and display.
4. Modular Programming: Separate concerns into reusable functions for clarity and
maintainability.

Practical 6: Material Quantity Calculator Using Lists

Objective: Write a Python program that uses lists to calculate the total quantity of materials
(e.g., cement, sand, and aggregate) required for multiple construction tasks.

Scenario: A construction project involves several tasks, each requiring specific quantities of
materials. The program allows the user to input quantities for each task, stores them in lists,
and calculates the total quantities for all tasks.

Code Example:

# Step 1: Initialize empty lists to store quantities for each material


cement_list = []
sand_list = []
aggregate_list = []

# Step 2: Input the number of tasks


print("=== Material Quantity Calculator ===")
num_tasks = int(input("Enter the number of construction tasks: "))

Dr. Vijaya Desai (vdesai@nicmar.ac.in)


NICMAR University BTech-Civil Introduction to Python [MDC406P]
School of Engineering Batch 1 – Sem IV Practical

# Step 3: Collect material quantities for each task


for i in range(1, num_tasks + 1):
print(f"\nTask {i}:")
cement = float(input("Enter the quantity of cement (in bags): "))
sand = float(input("Enter the quantity of sand (in cubic meters): "))
aggregate = float(input("Enter the quantity of aggregate (in cubic meters): "))

# Add the values to their respective lists


cement_list.append(cement)
sand_list.append(sand)
aggregate_list.append(aggregate)

# Step 4: Calculate total quantities using the sum() function


total_cement = sum(cement_list)
total_sand = sum(sand_list)
total_aggregate = sum(aggregate_list)

# Step 5: Display the results


print("\n=== Total Material Requirements ===")
print(f"Total Cement: {total_cement:.2f} bags")
print(f"Total Sand: {total_sand:.2f} cubic meters")
print(f"Total Aggregate: {total_aggregate:.2f} cubic meters")

# Optional: Display quantities for each task


print("\nMaterial Details Per Task:")
for i in range(num_tasks):
print(f"Task {i + 1}: Cement = {cement_list[i]:.2f} bags, Sand = {sand_list[i]:.2f} m³,
Aggregate = {aggregate_list[i]:.2f} m³")

Key Concepts Practiced:

1. Lists: Use lists to store quantities for each material.


2. Loops: Use a for loop to collect inputs for multiple tasks.
3. Built-in Functions: Use sum() to calculate total quantities from lists.
4. Input/Output: Take user inputs for material quantities and display results.
5. Indexing: Access and display quantities for each task using list indices.

Practical 7: Structural Load Distribution Using Arrays

Objective: Write a Python program to calculate and analyze the distribution of a uniformly
distributed load (UDL) across beams. Use NumPy arrays for efficient calculations.

Scenario: A beam is subjected to a uniformly distributed load (UDL). The user provides:

1. The total load (in kN).


2. The number of divisions or segments of the beam (to simulate discretized analysis).

The program calculates the load acting on each segment and stores the results in a NumPy
array.

Dr. Vijaya Desai (vdesai@nicmar.ac.in)


NICMAR University BTech-Civil Introduction to Python [MDC406P]
School of Engineering Batch 1 – Sem IV Practical

Code Example:

Install numpy library


Open your terminal or command prompt. Run the following command to install numpy
pip install numpy

import numpy as np

# Step 1: Input total load and number of segments


print("=== Structural Load Distribution Calculator ===")
total_load = float(input("Enter the total uniformly distributed load (UDL) on the beam (in
kN): "))
num_segments = int(input("Enter the number of segments to divide the beam into: "))

# Step 2: Calculate the load per segment


load_per_segment = total_load / num_segments

# Step 3: Create an array to store load distribution


load_array = np.full(num_segments, load_per_segment)

# Step 4: Display the load distribution


print("\n=== Load Distribution Across Beam Segments ===")
for i, load in enumerate(load_array, start=1):
print(f"Segment {i}: Load = {load:.2f} kN")

# Step 5: Additional Analysis (optional)


# Calculate total load to verify
calculated_total_load = np.sum(load_array)
print(f"\nCalculated Total Load: {calculated_total_load:.2f} kN (should match input load)")

Key Concepts Practiced:

1. Arrays (NumPy): Use np.full() to create an array filled with the same value (load per
segment). Use np.sum() to verify the total load.
2. Input/Output: Take user inputs for total load and number of segments. Display load
distribution for each segment.
3. Loops: Use a loop with enumerate() to display load values per segment.
4. Efficiency: NumPy arrays enable efficient numerical computations, especially for large
datasets.

Practical 8: Storing and Managing Building Floor Plans Using Dictionaries

Objective: Write a Python program that uses a dictionary to store and manage information
about building floor plans, such as the number of rooms, total area, and utility availability
(e.g., water, electricity) for each floor.

Dr. Vijaya Desai (vdesai@nicmar.ac.in)


NICMAR University BTech-Civil Introduction to Python [MDC406P]
School of Engineering Batch 1 – Sem IV Practical

Scenario: For a building project, the user needs to manage data for multiple floors. Each
floor has specific details:

1. Floor Number (Key in the dictionary).


2. Attributes: Number of rooms, total area, and utilities available (stored as a nested
dictionary).

The program allows the user to add data for multiple floors, retrieve details for a specific
floor, and display all data.

Code Example:

# Step 1: Initialize an empty dictionary to store floor data


building_data = {}

# Step 2: Define a function to add floor data


def add_floor_data(floor_number, num_rooms, total_area, utilities):
building_data[floor_number] = {
"Number of Rooms": num_rooms,
"Total Area (sq.m)": total_area,
"Utilities": utilities,
}

# Step 3: Define a function to retrieve data for a specific floor


def get_floor_data(floor_number):
if floor_number in building_data:
return building_data[floor_number]
else:
return f"No data available for Floor {floor_number}"

# Step 4: Define a function to display all floors


def display_all_floors():
if not building_data:
print("No floor data available.")
else:
print("\n=== Building Floor Plans ===")
for floor, data in building_data.items():
print(f"\nFloor {floor}:")
for key, value in data.items():
print(f" {key}: {value}")

# Step 5: Main program logic


print("=== Building Floor Plan Manager ===")
while True:
print("\nChoose an option:")
print("1. Add Floor Data")
print("2. View Floor Data")
print("3. Display All Floors")
print("4. Exit")
choice = input("Enter your choice: ")

Dr. Vijaya Desai (vdesai@nicmar.ac.in)


NICMAR University BTech-Civil Introduction to Python [MDC406P]
School of Engineering Batch 1 – Sem IV Practical

if choice == "1":
floor_number = input("Enter floor number: ")
num_rooms = int(input("Enter the number of rooms: "))
total_area = float(input("Enter total area (in sq.m): "))
utilities = input("Enter available utilities (e.g., water, electricity, gas): ")
add_floor_data(floor_number, num_rooms, total_area, utilities)
print(f"Data for Floor {floor_number} added successfully!")

elif choice == "2":


floor_number = input("Enter floor number to view data: ")
floor_data = get_floor_data(floor_number)
print("\n=== Floor Data ===")
if isinstance(floor_data, dict):
for key, value in floor_data.items():
print(f"{key}: {value}")
else:
print(floor_data)

elif choice == "3":


display_all_floors()

elif choice == "4":


print("Exiting the program. Goodbye!")
break

else:
print("Invalid choice. Please try again.")

Key Concepts Practiced:

1. Dictionaries: Store data using keys (floor numbers) and nested dictionaries for attributes.
2. Nested Data Structures: Use nested dictionaries to organize complex data (e.g., room
count, area, utilities).
3. Input/Output: Allow user interaction to manage data dynamically.
4. Modular Design: Functions for adding, retrieving, and displaying floor data.

Practical 9: Search for Specific Material Using Linear and Binary Search

Objective: Write a Python program that performs both linear search and binary search to
find a specific construction material from an inventory list. The program will allow the user
to input the material they are searching for and display the results using both search
algorithms.

Scenario: The program has a list of construction materials, each with a name, quantity, and
cost per unit. The user can search for a specific material by its name. The program will
perform both a linear search and a binary search to find the material. The binary search
requires the list to be sorted.

Dr. Vijaya Desai (vdesai@nicmar.ac.in)


NICMAR University BTech-Civil Introduction to Python [MDC406P]
School of Engineering Batch 1 – Sem IV Practical

Code Example: Linear Search and Binary Search

# Sample construction material inventory (unsorted for linear search, sorted for binary
search)
materials_inventory = [
{"name": "Cement", "quantity": 500, "cost_per_unit": 10.5},
{"name": "Steel", "quantity": 300, "cost_per_unit": 15.75},
{"name": "Sand", "quantity": 1000, "cost_per_unit": 2.25},
{"name": "Gravel", "quantity": 800, "cost_per_unit": 3.10},
{"name": "Bricks", "quantity": 2000, "cost_per_unit": 0.50}
]

# Linear Search Function


def linear_search(material_name, inventory):
for material in inventory:
if material["name"].lower() == material_name.lower():
return material
return None # Return None if material is not found

# Binary Search Function (requires sorted inventory)


def binary_search(material_name, inventory):
low = 0
high = len(inventory) - 1
while low <= high:
mid = (low + high) // 2
mid_material = inventory[mid]

# Compare the mid element with the target material


if mid_material["name"].lower() == material_name.lower():
return mid_material
elif mid_material["name"].lower() < material_name.lower():
low = mid + 1
else:
high = mid - 1
return None # Return None if material is not found

# Sort inventory by material name for binary search


sorted_inventory = sorted(materials_inventory, key=lambda x: x["name"].lower())

# Main program logic


print("=== Construction Material Search ===")
search_material = input("Enter the name of the material to search for: ")

# Perform Linear Search


linear_result = linear_search(search_material, materials_inventory)
if linear_result:
print("\nLinear Search Result:")
print(f"Material: {linear_result['name']}, Quantity: {linear_result['quantity']}, Cost per
Unit: ${linear_result['cost_per_unit']:.2f}")
else:

Dr. Vijaya Desai (vdesai@nicmar.ac.in)


NICMAR University BTech-Civil Introduction to Python [MDC406P]
School of Engineering Batch 1 – Sem IV Practical

print("\nMaterial not found using Linear Search.")

# Perform Binary Search


binary_result = binary_search(search_material, sorted_inventory)
if binary_result:
print("\nBinary Search Result:")
print(f"Material: {binary_result['name']}, Quantity: {binary_result['quantity']}, Cost per
Unit: ${binary_result['cost_per_unit']:.2f}")
else:
print("\nMaterial not found using Binary Search.")

Explanation of the Code:

1. Inventory List: The materials_inventory contains a list of dictionaries, each representing


a material with its name, quantity, and cost_per_unit.
2. Linear Search: The linear_search function iterates through the inventory and compares
the name of each material with the input. If a match is found, it returns the material’s
details.
3. Binary Search: The binary_search function performs a binary search, which requires a
sorted list. The list is sorted alphabetically by material name using the sorted() function
before performing the search.
4. The binary search works by repeatedly dividing the list into two halves and checking the
middle element. It eliminates half of the search space at each step.
5. Sorting: The inventory is sorted by material name using sorted() before performing the
binary search. The key=lambda x: x["name"].lower() ensures case-insensitive sorting.
6. User Input and Output: The program prompts the user to input a material name,
performs both searches, and displays the result from each search.

Key Concepts Practiced:

1. Linear Search: A simple algorithm that checks each element in the list sequentially. It
works on unsorted data.
2. Binary Search: A more efficient search algorithm that requires the data to be sorted. It
repeatedly divides the list into halves.
3. Sorting: Sorting is required for binary search. The inventory is sorted using Python's
built-in sorted() function.
4. Strings and Case Sensitivity: Both search functions use .lower() to make the search
case-insensitive.

Practical 10: Sort Material Data by Cost Using Bubble Sort and Quick Sort

Objective: Write a Python program that sorts a list of construction materials based on their
cost per unit using two different sorting algorithms: Bubble Sort and Quick Sort.

Scenario: You have an inventory of construction materials, and you need to sort them based
on their cost per unit. The program will sort the materials using Bubble Sort and Quick Sort,
and then display the sorted list.

Code Example: Sorting by Cost Using Bubble Sort and Quick Sort

Dr. Vijaya Desai (vdesai@nicmar.ac.in)


NICMAR University BTech-Civil Introduction to Python [MDC406P]
School of Engineering Batch 1 – Sem IV Practical

# Sample construction material inventory


materials_inventory = [
{"name": "Cement", "quantity": 500, "cost_per_unit": 10.5},
{"name": "Steel", "quantity": 300, "cost_per_unit": 15.75},
{"name": "Sand", "quantity": 1000, "cost_per_unit": 2.25},
{"name": "Gravel", "quantity": 800, "cost_per_unit": 3.10},
{"name": "Bricks", "quantity": 2000, "cost_per_unit": 0.50}
]

# Bubble Sort Function to sort by cost_per_unit


def bubble_sort(inventory):
n = len(inventory)
for i in range(n):
for j in range(0, n-i-1):
if inventory[j]["cost_per_unit"] > inventory[j+1]["cost_per_unit"]:
inventory[j], inventory[j+1] = inventory[j+1], inventory[j]
return inventory

# Quick Sort Function to sort by cost_per_unit


def quick_sort(inventory):
if len(inventory) <= 1:
return inventory
pivot = inventory[len(inventory) // 2]["cost_per_unit"]
left = [x for x in inventory if x["cost_per_unit"] < pivot]
middle = [x for x in inventory if x["cost_per_unit"] == pivot]
right = [x for x in inventory if x["cost_per_unit"] > pivot]
return quick_sort(left) + middle + quick_sort(right)

# Main program logic


print("=== Sorted Construction Material Inventory by Cost ===")

# Perform Bubble Sort


bubble_sorted_inventory = bubble_sort(materials_inventory.copy())
print("\nBubble Sort Result:")
for material in bubble_sorted_inventory:
print(f"Material: {material['name']}, Cost per Unit: ${material['cost_per_unit']:.2f},
Quantity: {material['quantity']}")

# Perform Quick Sort


quick_sorted_inventory = quick_sort(materials_inventory)
print("\nQuick Sort Result:")
for material in quick_sorted_inventory:
print(f"Material: {material['name']}, Cost per Unit: ${material['cost_per_unit']:.2f},
Quantity: {material['quantity']}")

Explanation of the Code:

1. Inventory List: The materials_inventory list contains dictionaries with each material's
name, quantity, and cost per unit.

Dr. Vijaya Desai (vdesai@nicmar.ac.in)


NICMAR University BTech-Civil Introduction to Python [MDC406P]
School of Engineering Batch 1 – Sem IV Practical

2. Bubble Sort: The bubble_sort function sorts the list by cost_per_unit using the bubble
sort algorithm.
3. It compares adjacent elements and swaps them if they are in the wrong order. This is
repeated for each item in the list.
4. Quick Sort: The quick_sort function sorts the list by cost_per_unit using the quick sort
algorithm.
5. It selects a pivot (middle element) and divides the list into three parts: elements less than
the pivot, elements equal to the pivot, and elements greater than the pivot.
6. The function recursively sorts the left and right parts.
7. Display Sorted Results: The program prints the sorted material inventory from both the
Bubble Sort and Quick Sort algorithms.

Key Concepts Practiced:

1. Sorting Algorithms: Understanding and implementing the Bubble Sort and Quick Sort
algorithms.
2. Lists and Dictionaries: Storing and manipulating complex data (materials) in lists of
dictionaries.
3. Recursion (Quick Sort): Using recursion to divide the list into smaller sublists and sort
them.
4. Iteration (Bubble Sort): Using nested loops to iterate through and sort the list.

Practical 11: Read construction material data, calculate the total cost for each material, and
write the results into a new file.

Objective: Write a Python program that reads data from a text file, processes the data, and
then writes the output to a new text file. This example demonstrates reading from and
writing to files using Python's built-in file handling functions.

Scenario: Imagine we have a text file containing construction material inventory data (name,
quantity, and cost per unit). The task is to read this data, process it (e.g., calculate the total
cost for each material), and write the results into a new file.

Code Example: Reading from and Writing to Files

1. Input File (materials.txt):

Let's assume the input file contains the following data (stored as a text file materials.txt):

Cement,500,10.5
Steel,300,15.75
Sand,1000,2.25
Gravel,800,3.10
Bricks,2000,0.50

2. Python Program:

# Define the input and output file paths


input_file = "materials.txt"
output_file = "processed_materials.txt"

Dr. Vijaya Desai (vdesai@nicmar.ac.in)


NICMAR University BTech-Civil Introduction to Python [MDC406P]
School of Engineering Batch 1 – Sem IV Practical

# Function to read from the input file and process the data
def read_and_process_file(input_file):
materials = []

# Open the input file and read data


try:
with open(input_file, 'r') as file:
for line in file:
# Split the line by commas to extract material data
name, quantity, cost_per_unit = line.strip().split(',')
materials.append({
'name': name,
'quantity': int(quantity),
'cost_per_unit': float(cost_per_unit),
'total_cost': int(quantity) * float(cost_per_unit)
})
except FileNotFoundError:
print(f"Error: The file {input_file} does not exist.")

return materials

# Function to write the processed data to the output file


def write_to_file(output_file, materials):
try:
with open(output_file, 'w') as file:
file.write("Material, Quantity, Cost per Unit, Total Cost\n") # Write header
for material in materials:
file.write(f"{material['name']}, {material['quantity']},
${material['cost_per_unit']:.2f}, ${material['total_cost']:.2f}\n")
print(f"Processed data has been written to {output_file}.")
except Exception as e:
print(f"Error writing to file: {e}")

# Main program execution


materials_data = read_and_process_file(input_file)
if materials_data:
write_to_file(output_file, materials_data)

Explanation:

1. Input File (materials.txt): This file contains a list of materials, with each line
representing a material's name, quantity, and cost per unit, separated by commas.
2. Reading from the File: The read_and_process_file function opens the input file
(materials.txt) in read mode ('r') and reads each line.
3. The strip() method is used to remove any leading/trailing whitespace, and split(',') is used
to break the line into the material's name, quantity, and cost per unit.

Dr. Vijaya Desai (vdesai@nicmar.ac.in)


NICMAR University BTech-Civil Introduction to Python [MDC406P]
School of Engineering Batch 1 – Sem IV Practical

4. The data is processed into a list of dictionaries, where each dictionary contains the
material's name, quantity, cost per unit, and the total cost (calculated as quantity *
cost_per_unit).
5. Writing to the File: The write_to_file function opens the output file
(processed_materials.txt) in write mode ('w') and writes the processed data.
6. It first writes a header line with column names.
7. Then it loops through the processed data and writes each material’s details into the file,
including the total cost.
8. File Error Handling: The program includes error handling using try-except blocks to
catch potential errors like file not found or write errors.

Key Concepts Practiced:

1. File Handling in Python: Using the open() function to read from and write to files.
2. Understanding file modes ('r' for reading, 'w' for writing).
3. Data Processing: Parsing and processing text data (e.g., splitting by commas and
converting to appropriate types).
4. Error Handling: Handling file-related errors (e.g., file not found) using try-except.
5. Writing Structured Data: Writing structured data to a new file in a readable format
(CSV-like).

Practical 12: Read soil_test data file, parse the data, and calculate the average moisture
content and shear strength of the samples

Objective: Write a Python program that reads data from a file, processes it, and extracts
useful information. This is useful in civil engineering tasks where data might be provided in
text files (e.g., soil test data, material inventory, survey results).

Scenario: We have a text file that contains soil test data. Each line contains information
about a soil sample, such as moisture content, density, and shear strength. The task is to read
this file, parse the data, and calculate the average moisture content and shear strength of the
samples.

Code Example: Parsing Soil Test Data from a File

1. Input File (soil_test_data.txt):

Let's assume the input file contains the following soil test data:

Sample1, 15.2, 1.6, 25.4


Sample2, 18.5, 1.8, 28.1
Sample3, 12.0, 1.5, 23.2
Sample4, 14.7, 1.7, 26.5
Sample5, 16.3, 1.6, 27.9

Where each line consists of:

• Sample name
• Moisture content (percentage)
• Density (g/cm³)

Dr. Vijaya Desai (vdesai@nicmar.ac.in)


NICMAR University BTech-Civil Introduction to Python [MDC406P]
School of Engineering Batch 1 – Sem IV Practical

• Shear strength (kPa)

2. Python Program:

# Define input file path


input_file = "soil_test_data.txt"

# Function to read and parse the soil test data


def parse_soil_test_data(input_file):
moisture_contents = []
densities = []
shear_strengths = []

# Open the file and read the data


try:
with open(input_file, 'r') as file:
for line in file:
# Split the line by commas and remove extra whitespace
data = line.strip().split(',')

# Extract each value and convert to appropriate types


sample_name = data[0]
moisture_content = float(data[1])
density = float(data[2])
shear_strength = float(data[3])

# Append the extracted values to respective lists


moisture_contents.append(moisture_content)
densities.append(density)
shear_strengths.append(shear_strength)

return moisture_contents, densities, shear_strengths

except FileNotFoundError:
print(f"Error: The file {input_file} does not exist.")
return [], [], []

# Function to calculate the average of a list


def calculate_average(values):
if values:
return sum(values) / len(values)
else:
return 0

# Main program execution


moisture_contents, densities, shear_strengths = parse_soil_test_data(input_file)

if moisture_contents and shear_strengths:


# Calculate average moisture content and shear strength
avg_moisture_content = calculate_average(moisture_contents)

Dr. Vijaya Desai (vdesai@nicmar.ac.in)


NICMAR University BTech-Civil Introduction to Python [MDC406P]
School of Engineering Batch 1 – Sem IV Practical

avg_shear_strength = calculate_average(shear_strengths)

# Display the results


print("=== Soil Test Data Analysis ===")
print(f"Average Moisture Content: {avg_moisture_content:.2f}%")
print(f"Average Shear Strength: {avg_shear_strength:.2f} kPa")
else:
print("No data available to process.")

Explanation:

1. Input File (soil_test_data.txt): The file contains comma-separated values for each soil
sample's moisture content, density, and shear strength.
2. Parsing the Data: The parse_soil_test_data() function opens the input file and reads each
line. It then splits the line by commas using split(',') to extract the values.
3. The function converts the extracted values to appropriate data types (float for numerical
values) and stores them in separate lists: moisture_contents, densities, and
shear_strengths.
4. Calculating Averages: The calculate_average() function computes the average value for
a given list of numbers by summing them and dividing by the length of the list.
5. Main Logic: The program reads the soil test data from the input file, parses it, calculates
the average moisture content and shear strength, and then displays the results.
6. Error Handling: The program checks if the input file exists and handles the
FileNotFoundError exception if the file is missing.

Key Concepts Practiced:

1. File Handling: Using open() to read from a file and handle file operations.
2. Data Parsing: Parsing text data (split by commas) to extract meaningful information.
3. Lists and Data Aggregation: Storing parsed data in lists and performing calculations
(e.g., average).
4. Error Handling: Handling missing file errors with try-except.

Practical 13: Numerical Computing Using NumPy Library: Calculate Young’s modulus
for each material sample, calculate maximum stress, average strain, and standard deviation of
strain. Perform matrix operations like the dot product using NumPy library

Objective: Write a Python program that uses the NumPy library for numerical computing.
This example demonstrates how to use NumPy for performing array-based operations, which
is commonly used in civil engineering tasks like structural analysis, material properties
calculations, or geotechnical analysis.

Scenario: We need to perform numerical operations like matrix multiplication, element-wise


operations, and statistical analysis (e.g., mean, median, standard deviation) on an array of
data. Let's assume we are working with some material property data (e.g., Young’s modulus,
stress, strain) and need to perform various operations.

Code Example: Numerical Computing with NumPy

Dr. Vijaya Desai (vdesai@nicmar.ac.in)


NICMAR University BTech-Civil Introduction to Python [MDC406P]
School of Engineering Batch 1 – Sem IV Practical

1. Installation (if NumPy is not installed) open command prompt and type

pip install numpy

2. Python Program:

import numpy as np

# Define some sample data (stress, strain, and Young's modulus)


stress = np.array([100, 150, 200, 250, 300]) # Stress in MPa
strain = np.array([0.005, 0.008, 0.010, 0.012, 0.015]) # Strain (dimensionless)

# Calculate Young's Modulus using the formula: E = Stress / Strain


# We assume that strain is non-zero for simplicity
youngs_modulus = stress / strain

# Perform element-wise operations (e.g., finding maximum stress, average strain)


max_stress = np.max(stress)
avg_strain = np.mean(strain)
std_dev_strain = np.std(strain)

# Matrix operations: Suppose we have two matrices for stress and strain measurements
matrix_stress = np.array([[100, 150], [200, 250]])
matrix_strain = np.array([[0.005, 0.008], [0.010, 0.012]])

# Matrix multiplication (dot product)


matrix_result = np.dot(matrix_stress, matrix_strain)

# Output the results


print("=== Numerical Computations using NumPy ===")
print(f"Stress data: {stress}")
print(f"Strain data: {strain}")
print(f"Young's Modulus (E): {youngs_modulus}")
print(f"Maximum Stress: {max_stress} MPa")
print(f"Average Strain: {avg_strain}")
print(f"Standard Deviation of Strain: {std_dev_strain}")

print(f"Matrix Multiplication of Stress and Strain Matrices:\n{matrix_result}")

Explanation:

1. Import NumPy: The program begins by importing the NumPy library with the alias np.
2. Data Definition: Arrays for stress and strain are defined using np.array(). These arrays
contain the stress and strain values for five different material tests.
3. Calculating Young's Modulus: Young’s modulus is calculated using the formula:
E=StressStrainE = \frac{\text{Stress}}{\text{Strain}}E=StrainStress This is done
element-wise for each pair of stress and strain values in the arrays.

Dr. Vijaya Desai (vdesai@nicmar.ac.in)


NICMAR University BTech-Civil Introduction to Python [MDC406P]
School of Engineering Batch 1 – Sem IV Practical

4. Element-wise Operations: Maximum stress (np.max()) is calculated to find the highest


stress value in the stress array.
5. Average strain (np.mean()) and standard deviation of strain (np.std()) are calculated
for strain values.
6. Matrix Operations: Two matrices (matrix_stress and matrix_strain) are created, and
their matrix multiplication is performed using np.dot(). The dot product of the two
matrices is calculated and stored in matrix_result.
7. Output: The program prints the following results:
o The calculated Young’s modulus for each material sample.
o The maximum stress, average strain, and standard deviation of strain.
o The result of the matrix multiplication of stress and strain matrices.

Key Concepts Practiced:

1. NumPy Arrays: Creating and manipulating arrays using NumPy. Element-wise


operations, which is a powerful feature in numerical computing.
2. Statistical Operations: Calculating the maximum, mean, and standard deviation of data,
which is useful in many engineering analyses.
3. Matrix Operations: Using NumPy to perform matrix operations like the dot product,
which is common in structural analysis and material science.

Practical 14: Using SciPy Library for scientific computing: Perform curve fitting on some
soil testing data (e.g., moisture content vs. shear strength) to model the relationship between
these two variables. Use SciPy's optimization and interpolation functions for analyzing the
data

Objective: Write a Python program using the SciPy library for scientific computing. SciPy
builds on NumPy and provides additional functionality, including optimization, integration,
interpolation, and statistics. This example demonstrates how to use SciPy for tasks commonly
needed in civil engineering, such as curve fitting, interpolation, and solving optimization
problems.

Scenario: We need to perform curve fitting on some soil testing data (e.g., moisture content
vs. shear strength) to model the relationship between these two variables. Then, we’ll use
SciPy's optimization and interpolation functions for analyzing the data.

Code Example: Using SciPy for Curve Fitting, Optimization, and Interpolation

1. Installation SciPy and matplotlib: open command prompt and run

pip install scipy


pip install matplotlib.pyplot

2. Python Program:

import numpy as np
import scipy.optimize as opt
import scipy.interpolate as interp
import matplotlib.pyplot as plt

Dr. Vijaya Desai (vdesai@nicmar.ac.in)


NICMAR University BTech-Civil Introduction to Python [MDC406P]
School of Engineering Batch 1 – Sem IV Practical

# Sample data (moisture content vs. shear strength)


moisture_content = np.array([5.0, 7.0, 9.0, 11.0, 13.0, 15.0]) # Moisture content in
percentage
shear_strength = np.array([25.4, 30.1, 32.5, 34.6, 35.8, 36.3]) # Shear strength in kPa

# 1. Curve Fitting - Linear Model


# We will fit the data to a linear model: y = a * x + b
def linear_model(x, a, b):
return a * x + b

# Use curve_fit from scipy.optimize to find the best-fitting parameters (a and b)


from scipy.optimize import curve_fit
params, covariance = curve_fit(linear_model, moisture_content, shear_strength)

a, b = params # Extracting parameters


print(f"Fitted linear model: y = {a:.2f}x + {b:.2f}")

# Plotting the curve fitting result


plt.scatter(moisture_content, shear_strength, color='blue', label='Data Points')
x_vals = np.linspace(5, 15, 100)
y_vals = linear_model(x_vals, *params)
plt.plot(x_vals, y_vals, color='red', label=f'Fitted Line: y = {a:.2f}x + {b:.2f}')
plt.xlabel('Moisture Content (%)')
plt.ylabel('Shear Strength (kPa)')
plt.legend()
plt.title('Moisture Content vs Shear Strength - Curve Fitting')
plt.show()

# 2. Optimization - Finding the minimum value of a quadratic function


# Define a quadratic function to represent soil behavior (hypothetical example)
def quadratic_function(x):
return 2 * x**2 - 3 * x + 5

# Use minimize function from scipy.optimize to find the minimum


result = opt.minimize(quadratic_function, 0) # Initial guess: x=0
print(f"Minimum value of the quadratic function occurs at x = {result.x[0]:.2f}")
print(f"Minimum value: {result.fun:.2f}")

# 3. Interpolation - Interpolating soil data for unknown moisture content values


# We'll use cubic interpolation to estimate shear strength at intermediate moisture contents
interpolator = interp.CubicSpline(moisture_content, shear_strength)

# Interpolating shear strength for moisture content values 6.5% and 14.5%
estimated_shear_strength_6_5 = interpolator(6.5)
estimated_shear_strength_14_5 = interpolator(14.5)
print(f"Estimated shear strength at 6.5% moisture content:
{estimated_shear_strength_6_5:.2f} kPa")
print(f"Estimated shear strength at 14.5% moisture content:
{estimated_shear_strength_14_5:.2f} kPa")

Dr. Vijaya Desai (vdesai@nicmar.ac.in)


NICMAR University BTech-Civil Introduction to Python [MDC406P]
School of Engineering Batch 1 – Sem IV Practical

Explanation:

1. Curve Fitting (SciPy's curve_fit):


o Data: We have moisture content and shear strength data from soil tests.
o Model: We use a linear model y = a * x + b to fit the data.
o SciPy Function: curve_fit() is used to find the best-fitting parameters a (slope)
and b (intercept) that minimize the difference between the model and the observed
data.
o Plotting: We use Matplotlib to plot the original data points and the fitted line.
2. Optimization (SciPy's minimize):
o We define a simple quadratic function f(x) = 2x^2 - 3x + 5 to represent some
hypothetical soil behavior.
o SciPy Function: minimize() finds the value of x that minimizes this function,
which is useful for optimization problems in civil engineering (e.g., finding the
most cost-effective material mix or optimizing structural design).
3. Interpolation (SciPy's CubicSpline):
o We use CubicSpline interpolation to estimate the shear strength for intermediate
values of moisture content (e.g., at 6.5% and 14.5% moisture content).
o SciPy Function: CubicSpline() creates a smooth curve that passes through all the
given data points, allowing us to predict values between the known data points.

Key Concepts Practiced:

1. Curve Fitting: Using curve_fit() for fitting models to data (linear or nonlinear).
2. Optimization: Using minimize() to find the minimum value of a function, useful for
engineering optimization problems.
3. Interpolation: Using CubicSpline() to interpolate and estimate values for intermediate
data points, crucial for analyzing soil properties at non-measured points.
4. SciPy for Scientific Computing: The program demonstrates how SciPy enhances
NumPy with more advanced functions for numerical computing, making it suitable for a
wide range of engineering and scientific applications.

Practical 15: Performing Mathematical Computations (operations such as matrix


multiplication, solving equations, basic arithmetic, and other useful mathematical tasks
common in engineering and scientific computations)

Objective: Write a Python program that performs basic and advanced mathematical
computations using Python’s built-in libraries and the NumPy library. The example will
showcase operations such as matrix multiplication, solving equations, basic arithmetic, and
other useful mathematical tasks common in engineering and scientific computations.

Scenario: Suppose we are analyzing the behavior of a material under stress and strain,
solving a system of linear equations related to structural analysis, and performing matrix
operations.

Code Example: Performing Mathematical Computations

Dr. Vijaya Desai (vdesai@nicmar.ac.in)


NICMAR University BTech-Civil Introduction to Python [MDC406P]
School of Engineering Batch 1 – Sem IV Practical

Installation (if NumPy is not installed):

pip install numpy

Python Code:

import numpy as np

# 1. Basic Arithmetic Computations


a = 25
b=5

# Addition, Subtraction, Multiplication, Division, and Exponentiation


sum_result = a + b
difference = a - b
product = a * b
division = a / b
exponentiation = a ** b

# Output basic arithmetic results


print("Basic Arithmetic Operations:")
print(f"{a} + {b} = {sum_result}")
print(f"{a} - {b} = {difference}")
print(f"{a} * {b} = {product}")
print(f"{a} / {b} = {division}")
print(f"{a} ^ {b} = {exponentiation}\n")

# 2. Matrix Operations using NumPy

# Define two matrices (e.g., for solving structural equilibrium equations)


matrix_A = np.array([[3, 4], [1, 2]])
matrix_B = np.array([[1, 3], [2, 5]])

# Matrix multiplication
matrix_product = np.dot(matrix_A, matrix_B)

# Matrix determinant and inverse


determinant_A = np.linalg.det(matrix_A)
inverse_A = np.linalg.inv(matrix_A) if determinant_A != 0 else "Not invertible"

# Output matrix operations results


print("Matrix Operations:")
print(f"Matrix A:\n{matrix_A}")
print(f"Matrix B:\n{matrix_B}")
print(f"Matrix A * Matrix B:\n{matrix_product}")
print(f"Determinant of Matrix A: {determinant_A}")
print(f"Inverse of Matrix A:\n{inverse_A}\n")

# 3. Solving Linear Equations using NumPy

Dr. Vijaya Desai (vdesai@nicmar.ac.in)


NICMAR University BTech-Civil Introduction to Python [MDC406P]
School of Engineering Batch 1 – Sem IV Practical

# Solving the system of equations:


# 3x + 4y = 10
# 1x + 2y = 3

# Coefficient matrix (A) and constants (b)


A = np.array([[3, 4], [1, 2]])
b = np.array([10, 3])

# Solve the system using np.linalg.solve()


solution = np.linalg.solve(A, b)

# Output the solution


print("Solving Linear Equations:")
print(f"Solution to the system of equations: x = {solution[0]:.2f}, y = {solution[1]:.2f}\n")

# 4. Statistical Computations
data = np.array([10, 12, 15, 19, 21, 22, 24])

# Mean, median, standard deviation, and variance


mean_value = np.mean(data)
median_value = np.median(data)
std_deviation = np.std(data)
variance = np.var(data)

# Output statistical results


print("Statistical Computations:")
print(f"Mean: {mean_value}")
print(f"Median: {median_value}")
print(f"Standard Deviation: {std_deviation}")
print(f"Variance: {variance}\n")

# 5. Trigonometric Computations
angle_in_radians = np.pi / 4 # 45 degrees in radians

# Sine, Cosine, Tangent


sine_value = np.sin(angle_in_radians)
cosine_value = np.cos(angle_in_radians)
tangent_value = np.tan(angle_in_radians)

# Output trigonometric results


print("Trigonometric Computations:")
print(f"sin(45 degrees): {sine_value}")
print(f"cos(45 degrees): {cosine_value}")
print(f"tan(45 degrees): {tangent_value}")

Explanation:

1. Basic Arithmetic Computations: Performs simple arithmetic operations (addition,


subtraction, multiplication, division, and exponentiation) using Python’s built-in
operators.

Dr. Vijaya Desai (vdesai@nicmar.ac.in)


NICMAR University BTech-Civil Introduction to Python [MDC406P]
School of Engineering Batch 1 – Sem IV Practical

2. Matrix Operations: Matrix Multiplication: Uses np.dot() to perform matrix


multiplication.
3. Determinant and Inverse: Uses np.linalg.det() to compute the determinant of a matrix
and np.linalg.inv() to compute the inverse (if the determinant is non-zero).
4. Solving Linear Equations: Solves a system of linear equations using np.linalg.solve() by
providing the coefficient matrix and the constants.
5. Statistical Computations: Computes the mean, median, standard deviation, and
variance of a data set using NumPy functions (np.mean(), np.median(), np.std(),
np.var()).
6. Trigonometric Computations: Computes the sine, cosine, and tangent of an angle (45
degrees, converted to radians) using NumPy’s np.sin(), np.cos(), and np.tan() functions.

Key Concepts Practiced:

1. Basic Arithmetic: Python’s built-in support for basic mathematical operations.


2. Matrix Operations: Using NumPy for advanced matrix operations, which are essential in
civil engineering for structural analysis, solving systems of equations, and more.
3. Solving Linear Systems: Applying NumPy's linear algebra capabilities to solve systems
of equations, a common task in engineering problems.
4. Statistical and Trigonometric Functions: Using NumPy to perform statistical analysis
and trigonometric computations, important for data analysis and engineering calculations.

Practical 16: Python Program to perform simulations for Structural Load Analysis and
traffic flow

Objective: This Python program will demonstrate how simulations can be applied to solve
real-world civil engineering problems. We will perform a Monte Carlo Simulation to
estimate the structural behavior of a building under random loads. Additionally, we will
simulate traffic flow using basic concepts like random variables and probability distributions,
which are commonly used in civil engineering tasks such as transportation and structural
analysis.

Scenario: Monte Carlo Simulation for Structural Load Analysis: We simulate random
variations in load factors (e.g., wind, snow, and live loads) to estimate the stress on a building
structure. Traffic Flow Simulation: We simulate the number of cars passing through a road
intersection over a fixed period and analyze congestion patterns.

Install Required Libraries: pip install numpy and pip install matplotlib

Python Code:

import numpy as np
import matplotlib.pyplot as plt

# 1. Monte Carlo Simulation for Structural Load Analysis

def simulate_structural_load(num_simulations):

Dr. Vijaya Desai (vdesai@nicmar.ac.in)


NICMAR University BTech-Civil Introduction to Python [MDC406P]
School of Engineering Batch 1 – Sem IV Practical

# Define the random distribution for the loads


# Example: Wind load (0-100 kN), Snow load (0-50 kN), Live load (10-30 kN)
wind_loads = np.random.uniform(0, 100, num_simulations)
snow_loads = np.random.uniform(0, 50, num_simulations)
live_loads = np.random.uniform(10, 30, num_simulations)

# Calculate total load on the building by summing individual loads


total_loads = wind_loads + snow_loads + live_loads

# Calculate statistics (mean, max, etc.)


mean_load = np.mean(total_loads)
max_load = np.max(total_loads)
min_load = np.min(total_loads)

# Output results
print(f"Structural Load Analysis Results (Out of {num_simulations} simulations):")
print(f"Mean Total Load: {mean_load:.2f} kN")
print(f"Maximum Total Load: {max_load:.2f} kN")
print(f"Minimum Total Load: {min_load:.2f} kN")

# Plot a histogram of the total loads


plt.hist(total_loads, bins=30, color='skyblue', edgecolor='black')
plt.title("Histogram of Total Structural Loads")
plt.xlabel("Total Load (kN)")
plt.ylabel("Frequency")
plt.show()

return mean_load, max_load, min_load

# 2. Traffic Flow Simulation (Poisson Distribution for Traffic Flow)

def simulate_traffic_flow(num_hours, avg_cars_per_hour):


# Simulate the number of cars arriving each hour (Poisson distribution)
traffic_data = np.random.poisson(avg_cars_per_hour, num_hours)

# Calculate statistics (mean, max, etc.)


mean_traffic = np.mean(traffic_data)
max_traffic = np.max(traffic_data)
total_traffic = np.sum(traffic_data)

# Output results
print(f"Traffic Flow Simulation Results (Over {num_hours} hours):")
print(f"Mean Traffic Flow: {mean_traffic:.2f} cars/hour")
print(f"Maximum Traffic Flow: {max_traffic} cars/hour")
print(f"Total Traffic Flow: {total_traffic} cars")

# Plot traffic data


plt.plot(range(num_hours), traffic_data, marker='o', linestyle='-', color='green')
plt.title("Traffic Flow Simulation (Cars per Hour)")

Dr. Vijaya Desai (vdesai@nicmar.ac.in)


NICMAR University BTech-Civil Introduction to Python [MDC406P]
School of Engineering Batch 1 – Sem IV Practical

plt.xlabel("Hour")
plt.ylabel("Number of Cars")
plt.show()

return mean_traffic, max_traffic, total_traffic

# Main Program Execution

# 1. Simulating Structural Loads


num_simulations = 10000 # Number of simulations for load analysis
mean_load, max_load, min_load = simulate_structural_load(num_simulations)

# 2. Simulating Traffic Flow


num_hours = 24 # Simulate traffic flow for 24 hours (1 day)
avg_cars_per_hour = 50 # Average number of cars passing per hour
mean_traffic, max_traffic, total_traffic = simulate_traffic_flow(num_hours,
avg_cars_per_hour)

Explanation:

1. Monte Carlo Simulation for Structural Load Analysis:

• Concept: In this simulation, we simulate random variations of three types of loads: wind,
snow, and live load (e.g., people or furniture). The np.random.uniform function generates
random numbers between specified ranges (e.g., wind load from 0 to 100 kN, snow load
from 0 to 50 kN, and live load from 10 to 30 kN).
• Total Load: The total load on the building is the sum of these loads.
• Statistics: We calculate the mean, maximum, and minimum total load.
• Visualization: The histogram of the total loads is plotted to visualize the distribution of
the loads.

2. Traffic Flow Simulation:

• Concept: Traffic flow is often modeled using a Poisson distribution, which is suitable
for modeling random events that occur independently over a fixed period. The
np.random.poisson function simulates the number of cars passing through an intersection
per hour.
• Statistics: We calculate the mean traffic flow, maximum traffic flow, and total traffic
flow over the simulation period (24 hours in this case).
• Visualization: The traffic flow over time (number of cars per hour) is plotted to visualize
traffic congestion patterns.

Key Concepts Practiced:

1. Monte Carlo Simulation: This method is widely used in civil engineering for risk
analysis, load testing, and probabilistic modeling of systems.
2. Poisson Distribution: A probability distribution used to model events that happen
randomly but at a constant average rate, such as traffic arrivals.

Dr. Vijaya Desai (vdesai@nicmar.ac.in)


NICMAR University BTech-Civil Introduction to Python [MDC406P]
School of Engineering Batch 1 – Sem IV Practical

3. Statistical Analysis: Calculating mean, max, and total values from simulated data to
make informed engineering decisions.
4. Visualization: Using Matplotlib to visualize simulation data, which is useful for
interpreting and communicating the results of civil engineering simulations.

Practical 17: Python Program for Data Visualization Using Matplotlib Library to plot a
bar chart to display material costs, a line chart to analyze stress-strain behaviour, a scatter
plot for traffic density analysis and a pie chart to display resource allocation in a
construction project

Objective: Create visualizations to represent civil engineering data using the Matplotlib
library to plot the following charts

1. A bar chart to display material costs.


2. A line chart to analyze stress-strain behavior.
3. A scatter plot for traffic density analysis.
4. A pie chart to display resource allocation in a construction project.

Install Required Libraries: pip install numpy and pip install matplotlib

Python Code:

import matplotlib.pyplot as plt


import numpy as np

# 1. Bar Chart: Material Costs

def bar_chart_material_costs(materials, costs):


plt.figure(figsize=(8, 6))
plt.bar(materials, costs, color='skyblue', edgecolor='black')
plt.title("Material Costs", fontsize=14)
plt.xlabel("Materials", fontsize=12)
plt.ylabel("Cost (per unit)", fontsize=12)
plt.grid(axis='y', linestyle='--', alpha=0.7)
plt.show()

# 2. Line Chart: Stress-Strain Behavior

def line_chart_stress_strain(strain, stress):


plt.figure(figsize=(8, 6))
plt.plot(strain, stress, marker='o', linestyle='-', color='red', label="Stress-Strain Curve")
plt.title("Stress-Strain Behavior", fontsize=14)
plt.xlabel("Strain", fontsize=12)
plt.ylabel("Stress (MPa)", fontsize=12)
plt.legend()
plt.grid(alpha=0.7)
plt.show()

Dr. Vijaya Desai (vdesai@nicmar.ac.in)


NICMAR University BTech-Civil Introduction to Python [MDC406P]
School of Engineering Batch 1 – Sem IV Practical

# 3. Scatter Plot: Traffic Density

def scatter_plot_traffic_density(locations, density):


plt.figure(figsize=(8, 6))
plt.scatter(locations, density, color='green', s=100, edgecolor='black', alpha=0.8)
plt.title("Traffic Density at Different Locations", fontsize=14)
plt.xlabel("Location", fontsize=12)
plt.ylabel("Traffic Density (vehicles/km)", fontsize=12)
plt.grid(alpha=0.7)
plt.show()

# 4. Pie Chart: Construction Resource Allocation

def pie_chart_resource_allocation(resources, percentages):


plt.figure(figsize=(8, 6))
plt.pie(percentages, labels=resources, autopct='%1.1f%%', startangle=140,
colors=plt.cm.Paired.colors)
plt.title("Construction Resource Allocation", fontsize=14)
plt.axis('equal') # Equal aspect ratio ensures the pie is drawn as a circle
plt.show()

# Main Program Execution

# Bar Chart Data: Material Costs


materials = ["Steel", "Cement", "Bricks", "Sand", "Wood"]
costs = [2000, 500, 300, 150, 1000] # Costs in local currency
bar_chart_material_costs(materials, costs)

# Line Chart Data: Stress-Strain Behavior


strain = np.linspace(0, 0.02, 10) # Example strain values
stress = 200 * strain # Example linear stress-strain relationship
line_chart_stress_strain(strain, stress)

# Scatter Plot Data: Traffic Density


locations = ["A", "B", "C", "D", "E"]
density = [50, 75, 60, 80, 90] # Vehicles per kilometer
scatter_plot_traffic_density(locations, density)

# Pie Chart Data: Resource Allocation


resources = ["Labor", "Materials", "Equipment", "Overheads"]
percentages = [40, 35, 15, 10] # Allocation in percentage
pie_chart_resource_allocation(resources, percentages)

Explanation:

1. Bar Chart: Scenario: Display the cost of materials (e.g., Steel, Cement, Bricks).
Purpose: Quickly compare material costs to help optimize budgets. Implementation:
Use plt.bar() with material names on the x-axis and costs on the y-axis.

Dr. Vijaya Desai (vdesai@nicmar.ac.in)


NICMAR University BTech-Civil Introduction to Python [MDC406P]
School of Engineering Batch 1 – Sem IV Practical

2. Line Chart: Scenario: Represent the stress-strain behavior of a material. Purpose:


Analyze how materials behave under different strain conditions. Implementation: Use
plt.plot() with strain values on the x-axis and stress on the y-axis.
3. Scatter Plot: Scenario: Visualize traffic density at different locations. Purpose: Identify
traffic congestion hotspots. Implementation: Use plt.scatter() with location names on the
x-axis and traffic density on the y-axis.
4. Pie Chart: Scenario: Show resource allocation in a construction project. Purpose:
Visualize the percentage of resources allocated to different categories. Implementation:
Use plt.pie() with percentages and resource names.

Practical 18: Python Program for Data Visualization Using Seaborn Library to plot
Material Costs using a bar plot, Traffic Density using a scatter plot with a regression line,
Load Distribution using a histogram and Correlation Matrix for analyzing relationships
among variables

Objective: The program demonstrates how to use the Seaborn library for creating advanced
and aesthetically pleasing visualizations for civil engineering data. The following
visualisation will be achieved through this program.

1. Material Costs using a bar plot.


2. Traffic Density using a scatter plot with a regression line.
3. Load Distribution using a histogram.
4. Correlation Matrix for analyzing relationships among variables.

Python Code:

Install Required Libraries (if they are not installed): pip install seaborn and pip install
matplotlib

Python Code:

import seaborn as sns


import matplotlib.pyplot as plt
import pandas as pd
import numpy as np

# 1. Bar Plot: Material Costs

def bar_plot_material_costs(data):
plt.figure(figsize=(8, 6))
sns.barplot(x="Material", y="Cost", data=data, palette="viridis")
plt.title("Material Costs", fontsize=14)
plt.xlabel("Materials", fontsize=12)
plt.ylabel("Cost (per unit)", fontsize=12)
plt.grid(axis='y', linestyle='--', alpha=0.7)
plt.show()

# 2. Scatter Plot with Regression: Traffic Density

Dr. Vijaya Desai (vdesai@nicmar.ac.in)


NICMAR University BTech-Civil Introduction to Python [MDC406P]
School of Engineering Batch 1 – Sem IV Practical

def scatter_plot_traffic_density(data):
plt.figure(figsize=(8, 6))
sns.regplot(x="Location ID", y="Traffic Density", data=data, color="green",
scatter_kws={'s': 100, 'alpha': 0.8})
plt.title("Traffic Density at Different Locations", fontsize=14)
plt.xlabel("Location ID", fontsize=12)
plt.ylabel("Traffic Density (vehicles/km)", fontsize=12)
plt.grid(alpha=0.7)
plt.show()

# 3. Histogram: Load Distribution

def histogram_load_distribution(loads):
plt.figure(figsize=(8, 6))
sns.histplot(loads, bins=20, kde=True, color='blue')
plt.title("Load Distribution", fontsize=14)
plt.xlabel("Load (kN)", fontsize=12)
plt.ylabel("Frequency", fontsize=12)
plt.grid(alpha=0.7)
plt.show()

# 4. Correlation Heatmap: Variables

def correlation_heatmap(data):
plt.figure(figsize=(8, 6))
correlation_matrix = data.corr()
sns.heatmap(correlation_matrix, annot=True, cmap="coolwarm", fmt=".2f")
plt.title("Correlation Matrix", fontsize=14)
plt.show()

# Main Program Execution

# Bar Plot Data: Material Costs


materials_data = pd.DataFrame({
"Material": ["Steel", "Cement", "Bricks", "Sand", "Wood"],
"Cost": [2000, 500, 300, 150, 1000] # Costs in local currency
})
bar_plot_material_costs(materials_data)

# Scatter Plot Data: Traffic Density


traffic_data = pd.DataFrame({
"Location ID": [1, 2, 3, 4, 5],
"Traffic Density": [50, 75, 60, 80, 90] # Vehicles per kilometer
})
scatter_plot_traffic_density(traffic_data)

# Histogram Data: Load Distribution

Dr. Vijaya Desai (vdesai@nicmar.ac.in)


NICMAR University BTech-Civil Introduction to Python [MDC406P]
School of Engineering Batch 1 – Sem IV Practical

loads = np.random.normal(100, 20, 1000) # Simulated random loads in kN


histogram_load_distribution(loads)

# Correlation Heatmap Data: Variables


correlation_data = pd.DataFrame({
"Load (kN)": np.random.normal(100, 20, 100),
"Stress (MPa)": np.random.normal(250, 30, 100),
"Traffic Density": np.random.normal(60, 15, 100),
"Material Cost (per unit)": np.random.uniform(100, 2000, 100)
})
correlation_heatmap(correlation_data)

Explanation:

1. Bar Plot: Material Costs:

• Scenario: Visualize the costs of construction materials.


• Purpose: Quickly compare material costs.
• Implementation: Use Seaborn’s sns.barplot() for an attractive bar chart.

2. Scatter Plot with Regression: Traffic Density:

• Scenario: Display the relationship between traffic density and location IDs, with a
regression line.
• Purpose: Identify trends in traffic congestion.
• Implementation: Use sns.regplot() to overlay a regression line on the scatter plot.

3. Histogram: Load Distribution:

• Scenario: Visualize the distribution of structural loads.


• Purpose: Analyze the frequency of different load values.
• Implementation: Use sns.histplot() for a histogram with a KDE (Kernel Density
Estimate) curve.

4. Correlation Heatmap: Variables:

• Scenario: Show the correlation between variables such as load, stress, traffic density,
and material costs.
• Purpose: Understand how variables relate to each other.
• Implementation: Use sns.heatmap() to create a heatmap of the correlation matrix.

Expected Output:

1. Bar Plot: A bar plot showing the costs of materials (Steel, Cement, Bricks, etc.).
2. Scatter Plot with Regression: A scatter plot showing traffic density with a regression
line, helping to identify trends.
3. Histogram: A histogram showing the distribution of structural loads.
4. Correlation Heatmap: A heatmap highlighting the correlation coefficients between
variables like load, stress, traffic density, and material costs.

Dr. Vijaya Desai (vdesai@nicmar.ac.in)


NICMAR University BTech-Civil Introduction to Python [MDC406P]
School of Engineering Batch 1 – Sem IV Practical

Source code and Output: Write a Python program to save the source code and its output to a text
file in the current working directory (CWD). Copy the content (source code and output) from the txt
file. Source code and output copied directly from the VS code will not be accepted. The Python code
is provided in the practical file. Additionally, save the chart files generated as output from any
practical and insert them as needed. Refer to the sample pages provided below.

Python code to write the source code and output to a new txt file in current working directory (CWD).
Please note you must display your Roll Number and Name in this program. Run this file by changing
the program file to create source code and output file for each practical. (e.g. in the following program
prg1.py is the name of python program file)

import sys #module provides access to system-specific parameters and functions


import io #module provides tools for handling file-like objects and in-memory streams

# Define file paths


source_file = "prg1.py" # Python practical file name
output_file = "source_and_output.txt" # The text file to save the code and output

# Step 1: Read the source code from the Python file


with open(source_file, "r") as src:
source_code = src.read()

# Step 2: Capture the output by redirecting sys.stdout


original_stdout = sys.stdout # Save the original stdout
captured_output = io.StringIO() # Create an in-memory file object to capture the
output
sys.stdout = captured_output # Redirect stdout to the in-memory object

# Step 3: Execute the source code


exec(source_code)

# Step 4: Write both the source code and the captured output to a text file
with open(output_file, "w") as output:
output.write("(Roll Number/Name)\nSource Code:\n")
output.write(source_code) # Write the source code
output.write("\n\nOutput:\n")
output.write(captured_output.getvalue()) # Write the captured output

# Step 5: Reset stdout to the original value


sys.stdout = original_stdout

print(f"Source code and output have been copied to '{output_file}'.")

OR

import subprocess

Dr. Vijaya Desai (vdesai@nicmar.ac.in)


NICMAR University BTech-Civil Introduction to Python [MDC406P]
School of Engineering Batch 1 – Sem IV Practical

# Define file paths

source_file = "p1.py"

output_file = "source_and_output.txt"

# Step 1: Read the source code

with open(source_file, "r") as src:

source_code = src.read()

# Step 2: Execute the script interactively (without capturing output)

with open(output_file, "w") as output:

output.write("(Roll Number/Name)\nSource Code:\n")

output.write(source_code) # Write the source code

output.write("\n\nOutput:\n")

# Run the script in real-time so input prompts are visible

process = subprocess.run(["python", source_file])

# Notify the user

print(f"Source code and output have been copied to '{output_file}'.")


# input prompts and input data both cannot be captured. Hence following code will execute the python
#file with input prompts with input data and repeat input data without input prompt for writing in text file

import subprocess

# Define file paths

source_file = "p1.py" # The Python script to execute

output_file = "source_and_output.txt"

# Step 1: Read and store the source code

Dr. Vijaya Desai (vdesai@nicmar.ac.in)


NICMAR University BTech-Civil Introduction to Python [MDC406P]
School of Engineering Batch 1 – Sem IV Practical

with open(source_file, "r") as src:

source_code = src.read()

# Step 2: Write the source code to the output file

with open(output_file, "w") as output:

output.write("Source Code:\n")

output.write(source_code)

output.write("\n\nExecution:\n")

# Step 3: Run script interactively (input prompts appear in terminal)

command = f'cmd /c "python {source_file}"'

subprocess.run(command, shell=True)

# Step 4: Capture the output manually

print("\nRe-enter the same input to capture it in the output file.")

with open(output_file, "a") as output:

process = subprocess.run(command, shell=True, text=True, stdout=output, stderr=output)

print(f"\n Source code, input, and output have been saved to '{output_file}'.")

Dr. Vijaya Desai (vdesai@nicmar.ac.in)

You might also like