Control Structures: Conditional Statements in Python
In this lab, you will learn about control structures, specifically conditional statements 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 and the Python extension is added to VS Code.
- Create a New File: Open VS Code and create a new Python file (e.g.,
conditional_statements_lab.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.
Exercises
Exercise 1: Simple If Statement
Task:
- Ask the user for their age.
- Print a message if the user is eligible to vote (age 18 or older).
Example Code:
# Get user input for age
age = int(input("Enter your age: "))
# Check if eligible to vote
if age >= 18:
print("You are eligible to vote.")
Exercise 2: If-Else Statement
Task:
- Ask the user for a number.
- Print whether the number is even or odd.
Example Code:
# Get user input for a number
number = int(input("Enter a number: "))
# Check if the number is even or odd
if number % 2 == 0:
print("The number is even.")
else:
print("The number is odd.")
Exercise 3: If-Elif-Else Statement
Task:
- Ask the user for their grade (0-100).
- Print the corresponding letter grade (A, B, C, D, F).
Example Code:
# Get user input for grade
grade = int(input("Enter your grade (0-100): "))
# Determine letter grade
if grade >= 90:
print("Your letter grade is A.")
elif grade >= 80:
print("Your letter grade is B.")
elif grade >= 70:
print("Your letter grade is C.")
elif grade >= 60:
print("Your letter grade is D.")
else:
print("Your letter grade is F.")
Exercise 4: Nested If Statements
Task:
- Ask the user for their height (in cm) and weight (in kg).
- Determine if they are classified as underweight, normal weight, overweight, or obese based on BMI.
Example Code:
# Get user input for height and weight
height = float(input("Enter your height in cm: ")) / 100 # Convert to meters
weight = float(input("Enter your weight in kg: "))
# Calculate BMI
bmi = weight / (height ** 2)
# Determine weight category
if bmi < 18.5:
print("You are classified as underweight.")
elif 18.5 <= bmi < 24.9:
print("You have a normal weight.")
elif 25 <= bmi < 29.9:
print("You are classified as overweight.")
else:
print("You are classified as obese.")
Running the Code
- Copy the Code: Copy the code examples provided above into your Python file.
- Run the Program: Execute the program in your IDE. You can usually do this by clicking a “Run” button or using a keyboard shortcut (like
Shift + F10
in PyCharm). - Interact with the Program: Follow the prompts in the console to input your data.
Conclusion
This lab helps you understand control structures and conditional statements in Python. By completing these exercises, you will gain practical experience in writing conditional logic to control the flow of your programs. Happy coding!
or
Lab 05: Control Structures—Conditional Statements (Civil Engineering Focus)
Objective: Use if
, elif
, and else
statements to solve engineering problems like load analysis, material selection, and safety compliance.
Key Concepts
- Conditional Logic:
if
: Execute code only if a condition is true.elif
: Check additional conditions if the first is false.else
: Execute code if all conditions are false.
- Civil Engineering Applications:
- Validate design parameters (e.g., beam deflection limits).
- Classify soil types based on lab data.
- Trigger safety alerts for equipment or structural failures.
Task 1: Beam Deflection Check
Problem:
A steel beam is safe if its deflection under load is ≤ 10 mm. Write a program to:
- Calculate deflection using the formula:
[
\delta = \frac{5 \cdot w \cdot L^4}{384 \cdot E \cdot I}
]
where (w) = distributed load (kN/m), (L) = span length (m), (E) = modulus of elasticity (GPa), (I) = moment of inertia (m⁴). - Classify the beam as Safe, Warning, or Unsafe based on deflection.
Sample Input:
Enter distributed load (kN/m): 8
Enter span length (m): 6
Enter modulus of elasticity (GPa): 200
Enter moment of inertia (m⁴): 0.0002
Sample Output:
Deflection: 11.25 mm
Status: UNSAFE (Exceeds 10 mm limit)
Solution Code:
w = float(input("Enter distributed load (kN/m): "))
L = float(input("Enter span length (m): "))
E = float(input("Enter modulus of elasticity (GPa): ")) * 1e9 # Convert to Pa
I = float(input("Enter moment of inertia (m⁴): "))
delta = (5 * w * 1000 * L**4) / (384 * E * I) # Convert kN to N for Pa consistency
delta_mm = delta * 1000 # Convert meters to mm
if delta_mm <= 10:
status = "SAFE"
elif delta_mm <= 12:
status = "WARNING (Monitor)"
else:
status = "UNSAFE (Exceeds 10 mm limit)"
print(f"\nDeflection: {delta_mm:.2f} mm")
print(f"Status: {status}")
Task 2: Soil Bearing Capacity Classification
Problem:
Classify soil based on its bearing capacity (kPa):
- Poor: < 100 kPa
- Fair: 100–200 kPa
- Good: > 200 kPa
Sample Input:
Enter bearing capacity (kPa): 175
Sample Output:
Soil Classification: Fair
Solution Code:
capacity = float(input("Enter bearing capacity (kPa): "))
if capacity < 100:
classification = "Poor"
elif 100 <= capacity <= 200:
classification = "Fair"
else:
classification = "Good"
print(f"\nSoil Classification: {classification}")
Task 3: Construction Site Safety Check
Problem:
A site is safe if:
- Wind speed ≤ 25 m/s and
- No heavy rain and
- All workers have PPE (Personal Protective Equipment).
Write a program to enforce safety protocols.
Sample Input:
Current wind speed (m/s): 28
Heavy rain? (yes/no): no
All workers have PPE? (yes/no): yes
Sample Output:
Wind Speed: 28 m/s → Exceeds 25 m/s limit
Heavy Rain: False
PPE Compliance: True
Site Status: UNSAFE (High wind)
Solution Code:
wind = float(input("Current wind speed (m/s): "))
rain = input("Heavy rain? (yes/no): ").lower() == "yes"
ppe = input("All workers have PPE? (yes/no): ").lower() == "yes"
safe_wind = wind <= 25
safe_rain = not rain
safe_ppe = ppe
if safe_wind and safe_rain and safe_ppe:
print("Site Status: SAFE")
else:
issues = []
if not safe_wind:
issues.append("High wind")
if not safe_rain:
issues.append("Heavy rain")
if not safe_ppe:
issues.append("Missing PPE")
print(f"Site Status: UNSAFE ({', '.join(issues)})")
Task 4: Material Selection Using Match-Case (Python 3.10+)
Problem:
Select construction materials based on project type:
- Bridge: “High-Strength Steel”
- Residential: “Reinforced Concrete”
- Road: “Asphalt”
- Default: “Consult Engineer”
Sample Input:
Enter project type: Bridge
Sample Output:
Recommended Material: High-Strength Steel
Solution Code:
project_type = input("Enter project type: ").title()
match project_type:
case "Bridge":
material = "High-Strength Steel"
case "Residential":
material = "Reinforced Concrete"
case "Road":
material = "Asphalt"
case _:
material = "Consult Engineer"
print(f"\nRecommended Material: {material}")
Key Takeaways
- Decision-Making: Use
if-elif-else
to enforce engineering standards (e.g., deflection limits). - Complex Conditions: Combine logical operators (
and
,or
,not
) for multi-factor safety checks. - Edge Cases: Always handle unexpected inputs (e.g., negative bearing capacities).
Challenge Problem
Problem:
A retaining wall fails if:
- Overturning safety factor < 1.5 OR
- Sliding safety factor < 1.2 OR
- Bearing capacity < 200 kPa.
Write a program to evaluate stability.
Sample Input:
Overturning SF: 1.4
Sliding SF: 1.3
Bearing capacity (kPa): 250
Sample Output:
Overturning SF: 1.4 → FAIL
Sliding SF: 1.3 → PASS
Bearing Capacity: 250 kPa → PASS
Wall Status: FAIL (Overturning)
Solution Snippet:
overturning_sf = float(input("Overturning SF: "))
sliding_sf = float(input("Sliding SF: "))
bearing_capacity = float(input("Bearing capacity (kPa): "))
fail_conditions = []
if overturning_sf < 1.5:
fail_conditions.append("Overturning")
if sliding_sf < 1.2:
fail_conditions.append("Sliding")
if bearing_capacity < 200:
fail_conditions.append("Bearing")
if not fail_conditions:
print("Wall Status: PASS")
else:
print(f"Wall Status: FAIL ({', '.join(fail_conditions)})")