PythonPracticals
PythonPracticals
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
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:
Task Description: Write a Python program that calculates the total construction cost for a
project based on user inputs for the following:
Code Example:
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"
optional_costs = 0
if landscaping:
optional_costs += 5000 # Fixed cost for landscaping
if electrical:
optional_costs += 7000 # Fixed cost for electrical work
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:
Code Example:
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.
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
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:
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:
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:
The program calculates the load acting on each segment and stores the results in a NumPy
array.
Code Example:
import numpy as np
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.
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.
Scenario: For a building project, the user needs to manage data for multiple floors. Each
floor has specific details:
The program allows the user to add data for multiple floors, retrieve details for a specific
floor, and display all data.
Code Example:
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!")
else:
print("Invalid choice. Please try again.")
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.
# 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}
]
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
1. Inventory List: The materials_inventory list contains dictionaries with each material's
name, quantity, and cost per unit.
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.
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.
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:
# Function to read from the input file and process the data
def read_and_process_file(input_file):
materials = []
return materials
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.
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.
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.
Let's assume the input file contains the following soil test data:
• Sample name
• Moisture content (percentage)
• Density (g/cm³)
2. Python Program:
except FileNotFoundError:
print(f"Error: The file {input_file} does not exist.")
return [], [], []
avg_shear_strength = calculate_average(shear_strengths)
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.
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.
1. Installation (if NumPy is not installed) open command prompt and type
2. Python Program:
import numpy as np
# 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]])
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.
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
2. Python Program:
import numpy as np
import scipy.optimize as opt
import scipy.interpolate as interp
import matplotlib.pyplot as plt
# 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")
Explanation:
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.
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.
Python Code:
import numpy as np
# Matrix multiplication
matrix_product = np.dot(matrix_A, matrix_B)
# 4. Statistical Computations
data = np.array([10, 12, 15, 19, 21, 22, 24])
# 5. Trigonometric Computations
angle_in_radians = np.pi / 4 # 45 degrees in radians
Explanation:
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
def simulate_structural_load(num_simulations):
# 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")
# 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")
plt.xlabel("Hour")
plt.ylabel("Number of Cars")
plt.show()
Explanation:
• 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.
• 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.
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.
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
Install Required Libraries: pip install numpy and pip install matplotlib
Python Code:
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.
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.
Python Code:
Install Required Libraries (if they are not installed): pip install seaborn and pip install
matplotlib
Python Code:
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()
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()
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()
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()
Explanation:
• 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.
• 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.
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)
# 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
OR
import subprocess
source_file = "p1.py"
output_file = "source_and_output.txt"
source_code = src.read()
output.write("\n\nOutput:\n")
import subprocess
output_file = "source_and_output.txt"
source_code = src.read()
output.write("Source Code:\n")
output.write(source_code)
output.write("\n\nExecution:\n")
subprocess.run(command, shell=True)
print(f"\n Source code, input, and output have been saved to '{output_file}'.")