In this lab, you will practice basic input/output operations and string manipulation in Python. You can perform the exercises in any of the following environments:
- Visual Studio Code (VS Code)
- Google Colab
- Jupyter Notebook
- PyCharm
- Anaconda
Setup Instructions
1. Visual Studio Code (VS Code)
- Installation: Ensure Python is installed on your system. Install the Python extension for VS Code.
- Create a New File: Open VS Code and create a new Python file e.g:
lab02.py
- Run the code: Use the editor’s terminal or run button to execute your code.
2. Google Colab
- Access Colab: Go to Google Colab.
- Create a New Notebook: Click on “New Notebook.”
- Run Cells: Write your code in a cell and run it by clicking the play button.
3. Jupyter Notebook
- Installation: Install Jupyter Notebook via Anaconda or Pip.
- Start Jupyter: Open your terminal and type
jupyter notebook
to launch. - Create a New Notebook: Create a new Python notebook and write your code in the cells.
4. PyCharm
- Installation: Download and install PyCharm.
- Create a New Project: Start a new project and create a new Python file.
- Run the code: Write and run your code using the built-in run configuration.
5. Anaconda
- Launch Anaconda Navigator: Open Anaconda Navigator.
- Choose an Environment: Launch either Jupyter Notebook or Spyder.
- Create a New File/Notebook: Write your code in a new notebook or script.
Basic Input/Output and String Operations in Python
Python provides simple functions to handle input and output operations and powerful string manipulation capabilities.
1. Input and Output in Python
1.1 Output (print()
function)
The print()
function is used to display output.
Example:
print("Hello, World!") # Output: Hello, World!
Printing multiple values:
name = "Alice"
age = 25
print("Name:", name, "Age:", age)
# Output: Name: Alice Age: 25
Using f-strings (Formatted Strings)
print(f"Name: {name}, Age: {age}")
# Output: Name: Alice, Age: 25
1.2 Input (input()
function)
The input()
function allows user input.
Example:
user_name = input("Enter your name: ")
print(f"Hello, {user_name}!")
Note: input()
always returns a string.
Converting Input Data Type
age = int(input("Enter your age: ")) # Converts input to an integer
print(f"You will be {age + 1} next year.")
2. String Operations in Python
2.1 String Concatenation
str1 = "Hello"
str2 = "World"
result = str1 + " " + str2
print(result) # Output: Hello World
2.2 String Repetition
text = "Python "
print(text * 3) # Output: Python Python Python
2.3 Accessing Characters in a String
word = "Python"
print(word[0]) # Output: P (First character)
print(word[-1]) # Output: n (Last character)
2.4 String Slicing
text = "Programming"
print(text[0:5]) # Output: Progr (Substring from index 0 to 4)
print(text[:6]) # Output: Progra (Substring from start to index 5)
print(text[4:]) # Output: ramming (Substring from index 4 to end)
2.5 String Length (len()
)
text = "Python"
print(len(text)) # Output: 6
3. String Methods
Python provides several built-in string methods.
Method | Description | Example |
---|---|---|
lower() | Converts to lowercase | "Hello".lower() → "hello" |
upper() | Converts to uppercase | "Hello".upper() → "HELLO" |
strip() | Removes whitespace | " Hello ".strip() → "Hello" |
replace(a, b) | Replaces a with b | "Hello".replace("H", "J") → "Jello" |
split() | Splits into a list | "a,b,c".split(",") → ["a", "b", "c"] |
join() | Joins elements with a separator | ",".join(["a", "b", "c"]) → "a,b,c" |
Example:
message = " Hello, World! "
print(message.lower()) # hello, world!
print(message.upper()) # HELLO, WORLD!
print(message.strip()) # Hello, World!
print(message.replace("World", "Python")) # Hello, Python!
4. Checking Substrings
text = "Python is fun"
print("Python" in text) # Output: True
print("Java" not in text) # Output: True
5. String Formatting
Using .format()
name = "Alice"
age = 25
print("My name is {} and I am {} years old.".format(name, age))
Using f-strings (Recommended)
print(f"My name is {name} and I am {age} years old.")
These are the basic input/output and string operations in Python.🚀
Exercises
Exercise 1: User Greeting
Task:
- Write a program asking the user for their first and last names.
- Concatenate the names and display a greeting message.
Example Code:
# Get user input for first and last name
first_name = input("Enter your first name: ")
last_name = input("Enter your last name: ")
# Concatenate names and display greeting
full_name = first_name + " " + last_name
print("Hello, " + full_name + "!")
Exercise 2: String Analysis
Task:
- Ask the user to enter a sentence.
- Display the original sentence, the number of characters, the sentence in uppercase, and the stripped sentence.
Example Code:
# Get user input for a sentence
sentence = input("Enter a sentence: ")
# Analyze the string
length = len(sentence)
uppercase_sentence = sentence.upper()
stripped_sentence = sentence.strip()
# Display results
print("Original Sentence:", sentence)
print("Number of Characters:", length)
print("Uppercase:", uppercase_sentence)
print("Stripped Sentence:", stripped_sentence)
Exercise 3: Word Count
Task:
- Ask the user to enter a paragraph.
- Count and display the number of words in the paragraph.
Example Code:
# Get user input for a paragraph
paragraph = input("Enter a paragraph: ")
# Count words
word_count = len(paragraph.split())
# Display word count
print("Word Count:", word_count)
Conclusion
Complete the exercises in your chosen environment. This lab will help reinforce your understanding of basic input/output and string operations in Python. Enjoy coding!
Watch Vidio
or
Lab 02: Basic Input/Output and String Operations (Civil Engineering Focus)
Objective: Practice Python input/output, string manipulation, and formatting with real-world civil engineering applications.
Task 1: Concrete Mix Ratio Calculator
Problem:
Design a program to calculate the total volume of concrete required for a project based on user-input mix ratios (e.g., 1:2:4 for cement:sand:aggregate).
Steps:
- Prompt the user for:
- Mix ratio (e.g., “1:2:4”)
- Total cement volume (in cubic meters)
- Parse the mix ratio string to extract proportions.
- Calculate the volumes of sand and aggregate.
- Print the results in a formatted table.
Sample Input:
Enter mix ratio (cement:sand:aggregate): 1:2:4
Enter cement volume (m³): 3
Sample Output:
Concrete Mix Breakdown:
- Cement: 3.00 m³
- Sand: 6.00 m³
- Aggregate: 12.00 m³
Total Volume: 21.00 m³
Hint:
- Use
split(':')
to parse the ratio. - Use f-strings for formatting (e.g.,
{sand:.2f}
).
Task 2: Soil Classification Parser
Problem:
Soil test data is often recorded as strings (e.g., “CL-ML: Silty Clay with Sand, LL=45, PL=22”). Write a program to extract key properties.
Steps:
- Prompt the user for a soil classification string.
- Extract:
- Soil type (e.g., “CL-ML”)
- Liquid Limit (LL)
- Plastic Limit (PL)
- Calculate the Plasticity Index (PI = LL – PL).
- Print the results in a structured format.
Sample Input:
Enter soil classification: CL-ML: Silty Clay with Sand, LL=45, PL=22
Sample Output:
Soil Type: CL-ML
Liquid Limit (LL): 45
Plastic Limit (PL): 22
Plasticity Index (PI): 23
Hint:
- Use
split(',')
andsplit('=')
to isolate values. - Remove spaces with
replace(" ", "")
.
Task 3: Structural Load Formatter
Problem:
Convert a list of loads (input as a string) into a clean report.
Input Format:
"Column A: 2500 kN, Column B: 1800 kN, Beam C: 1200 kN"
Steps:
- Parse the input string into individual load entries.
- Extract the component name and load value.
- Sort components alphabetically.
- Write the sorted data to a text file
load_report.txt
.
Sample Output File:
Load Report:
- Beam C: 1200 kN
- Column A: 2500 kN
- Column B: 1800 kN
Hint:
- Use
split(', ')
to separate entries. - Use
sorted()
to sort components.
Task 4: CSV Data Analyzer for Bridge Sensors
Problem:
A CSV file (sensor_data.csv
) contains bridge vibration readings. Write a program to:
- Read the file.
- Calculate the average vibration amplitude.
- Flag readings exceeding 10 mm (potential damage).
CSV Example:
Sensor_ID,Reading (mm),Time (s)
S1,5.2,0
S2,12.7,5
S3,8.3,10
Sample Output:
Average Vibration: 8.73 mm
Alerts:
- Sensor S2: 12.70 mm (Exceeds 10 mm threshold)
Hint:
- Use
csv.reader
to parse the file. - Skip the header row with
next(reader)
.
Solutions & Code Snippets
Task 1 Solution:
mix_ratio = input("Enter mix ratio (cement:sand:aggregate): ")
cement = float(input("Enter cement volume (m³): "))
parts = list(map(float, mix_ratio.split(':')))
sand = cement * parts[1] / parts[0]
aggregate = cement * parts[2] / parts[0]
total = cement + sand + aggregate
print(f"\nConcrete Mix Breakdown:")
print(f"- Cement: {cement:.2f} m³")
print(f"- Sand: {sand:.2f} m³")
print(f"- Aggregate: {aggregate:.2f} m³")
print(f"Total Volume: {total:.2f} m³")
Task 2 Solution:
soil_data = input("Enter soil classification: ").replace(" ", "")
soil_type = soil_data.split(':')[0]
ll = int(soil_data.split('LL=')[1].split(',')[0])
pl = int(soil_data.split('PL=')[1])
pi = ll - pl
print(f"\nSoil Type: {soil_type}")
print(f"Liquid Limit (LL): {ll}")
print(f"Plastic Limit (PL): {pl}")
print(f"Plasticity Index (PI): {pi}")
Key Takeaways
- String Manipulation: Use
split()
,replace()
, and slicing to extract data from unstructured text. - File I/O: Read/write files (
open()
,csv.reader
) for real-world data processing. - Formatting: Use f-strings to present results clearly (critical for engineering reports).
Next Step: Try modifying Task 4 to calculate the maximum vibration and export alerts to a new CSV file! 🚀
Lab 02: Enhanced Solutions & Explanations
Objective: Refine input/output handling, string parsing, and error checking for civil engineering applications.
Task 1: Concrete Mix Ratio Calculator (Robust Version)
Improvements:
- Added input validation to handle non-numeric values.
- Ensured mix ratio has exactly 3 parts.
try:
mix_ratio = input("Enter mix ratio (cement:sand:aggregate): ")
parts = list(map(float, mix_ratio.split(':')))
if len(parts) != 3:
raise ValueError("Mix ratio must have 3 parts (e.g., 1:2:4).")
cement = float(input("Enter cement volume (m³): "))
if cement <= 0:
raise ValueError("Cement volume must be positive.")
sand = cement * parts[1] / parts[0]
aggregate = cement * parts[2] / parts[0]
total = cement + sand + aggregate
print(f"\nConcrete Mix Breakdown:")
print(f"- Cement: {cement:.2f} m³")
print(f"- Sand: {sand:.2f} m³")
print(f"- Aggregate: {aggregate:.2f} m³")
print(f"Total Volume: {total:.2f} m³")
except ValueError as e:
print(f"Error: {e}")
Task 2: Soil Classification Parser (Using Regular Expressions)
Improvements:
- Used regex to robustly extract values regardless of input order or spacing.
import re
soil_data = input("Enter soil classification: ")
# Extract components using regex
soil_type = re.search(r"^([A-Z-]+):", soil_data).group(1)
ll_match = re.search(r"LL=(\d+)", soil_data)
pl_match = re.search(r"PL=(\d+)", soil_data)
if not (ll_match and pl_match):
print("Error: Missing LL or PL values.")
else:
ll = int(ll_match.group(1))
pl = int(pl_match.group(1))
pi = ll - pl
print(f"\nSoil Type: {soil_type}")
print(f"Liquid Limit (LL): {ll}")
print(f"Plastic Limit (PL): {pl}")
print(f"Plasticity Index (PI): {pi}")
Task 3: Structural Load Formatter (With File Context Manager)
Improvements:
- Used
with
statement for safe file handling. - Handled inconsistent spacing in input.
load_input = input("Enter loads (e.g., 'Column A:2500 kN, Beam B: 1800 kN'): ").replace(" ", "")
entries = load_input.split(',')
loads = []
for entry in entries:
if ':' in entry:
component, value = entry.split(':', 1)
loads.append((component.strip(), value.strip()))
# Sort and write to file
with open("load_report.txt", "w") as file:
file.write("Load Report:\n")
for component, value in sorted(loads, key=lambda x: x[0]):
file.write(f"- {component}: {value}\n")
print("Report saved to load_report.txt")
Task 4: CSV Data Analyzer (Enhanced with Error Handling)
Improvements:
- Added checks for missing/incorrect data.
- Calculated maximum vibration and exported alerts.
import csv
try:
with open("sensor_data.csv", "r") as file:
reader = csv.reader(file)
header = next(reader) # Skip header
readings = []
alerts = []
for row in reader:
if len(row) < 3:
continue # Skip malformed rows
sensor_id, reading, time = row
try:
reading = float(reading)
readings.append(reading)
if reading > 10:
alerts.append((sensor_id, reading))
except ValueError:
print(f"Invalid reading for {sensor_id}: {reading}")
if not readings:
print("No valid data found.")
else:
avg = sum(readings) / len(readings)
max_vibration = max(readings)
print(f"Average Vibration: {avg:.2f} mm")
print(f"Maximum Vibration: {max_vibration:.2f} mm")
if alerts:
print("\nAlerts:")
for sensor, val in alerts:
print(f"- Sensor {sensor}: {val:.2f} mm (Exceeds 10 mm threshold)")
# Export alerts to CSV
with open("alerts.csv", "w", newline='') as alert_file:
writer = csv.writer(alert_file)
writer.writerow(["Sensor_ID", "Reading (mm)"])
writer.writerows(alerts)
print("\nAlerts exported to alerts.csv")
except FileNotFoundError:
print("Error: sensor_data.csv not found.")
Key Takeaways for Students
- Input Validation: Always check for valid numeric inputs and format consistency.
- Robust Parsing: Use regex for complex string extraction instead of brittle
split()
operations. - Safe File Handling: Use
with
statements to prevent resource leaks. - Error Messaging: Provide clear feedback for invalid inputs or file issues.
Challenge: Modify Task 4 to also calculate the standard deviation of vibrations and highlight sensors exceeding 2 standard deviations! 🔍