Conditional Blocks
Conditional blocks are sections of code that run only when certain conditions are true. They help programs make decisions.
if statement
The if
statement checks a condition and runs code only if that condition is True.
Example:
x = 10 if x > 5: print("x is greater than 5")
Explanation: This will print the message because x (10) is indeed greater than 5.
else statement
The else
statement comes after if
and runs when the if
condition is False.
Example:
x = 3 if x > 5: print("x is greater than 5") else: print("x is 5 or smaller")
Explanation: This will print "x is 5 or smaller" because 3 is not greater than 5.
elif statement (else if)
elif
(short for "else if") checks another condition when the previous conditions were False.
Example:
x = 5 if x > 5: print("x is greater than 5") elif x == 5: print("x is exactly 5") else: print("x is smaller than 5")
Explanation: This will print "x is exactly 5" because the first condition is False but the second is True.
Important Notes
- - Conditions must end with a colon (:)
- - The code to run must be indented (usually 4 spaces)
- - You can have multiple
elif
statements else
comes last and doesn't need a condition- - Conditions can use comparison operators like ==, !=, <, >, <=, >=
Example
temperature = 85 if temperature > 100: print("Danger! Overheating!") elif temperature > 80: print("Warning: High temperature") elif temperature > 50: print("Normal operating range") else: print("Warning: Low temperature")
This shows how conditional blocks can be used to monitor systems in engineering applications.
Simple For Loop
A for loop repeats code for each item in a sequence (like a list, string, or range).
Basic Syntax:
for item in sequence: # do something with item
For Loop with Range
range()
creates a sequence of numbers for the loop to go through.
Examples:
# Loop from 0 to 4 for i in range(5): print(i) # prints 0,1,2,3,4 # Loop from 2 to 6 for i in range(2, 7): print(i) # prints 2,3,4,5,6 # Loop from 0 to 10 in steps of 2 for i in range(0, 11, 2): print(i) # prints 0,2,4,6,8,10
For Loop with Strings
You can loop through each character in a string.
Example:
word = "engineer" for letter in word: print(letter) # prints e,n,g,i,n,e,e,r (each on new line)
For Loop with Lists
You can loop through each item in a list.
Example:
tools = ["hammer", "wrench", "screwdriver"] for tool in tools: print(f"Use the {tool}") # prints each tool name with "Use the" before it
For Loop with Dictionaries
Dictionaries need special methods to loop through keys, values, or both.
Examples:
car = {"brand": "Toyota", "model": "Corolla", "year": 2020} # Loop through keys for key in car.keys(): print(key) # prints brand, model, year # Loop through values for value in car.values(): print(value) # prints Toyota, Corolla, 2020 # Loop through both (items) for key, value in car.items(): print(f"{key}: {value}") # prints brand: Toyota, model: Corolla, year: 2020
Important Notes
- - Always end the for statement with a colon (:)
- - The loop code must be indented
- - You can use
break
to stop the loop early - - Use
continue
to skip to the next item - - You can use
else:
after a for loop (runs if loop completes normally)
Example
# Calculate total resistance in parallel circuit resistances = [10, 20, 30] # in ohms total = 0 for r in resistances: total += 1/r equivalent_resistance = 1/total print(f"Equivalent resistance: {equivalent_resistance:.2f} ohms")
This shows how for loops can be used in engineering calculations.
Python While Loops
1. What is a While Loop?
A while loop repeats a block of code as long as a condition is true. Unlike for loops that run for a set number of times, while loops run until the condition becomes false.
2. Basic Syntax
while condition: # code to execute # remember to update the condition
3. Simple Example
count = 0 while count < 5: print(f"Count is {count}") count += 1 # Important: Don't forget to update the counter!
Output: Prints "Count is 0" to "Count is 4"
4. Key Features
- - Condition Check: The loop checks the condition before each iteration
- - Infinite Loops: If the condition never becomes false, the loop runs forever
- - Control Statements: You can use
break
to exit orcontinue
to skip to next iteration
5. Examples
a) Sensor Data Reading
temperature = 25 while temperature < 100: print(f"Current temperature: {temperature}°C") temperature += 15 # Simulating temperature rise if temperature > 80: print("Warning: Approaching critical temperature!") print("System overheating! Shutting down...")
b) User Input Validation
while True: user_input = input("Enter engine RPM (800-6000): ") if user_input.isdigit() and 800 <= int(user_input) <= 6000: print("Valid RPM entered") break else: print("Invalid input! Try again.")
c) Convergence Calculation
tolerance = 0.0001 error = 1.0 x = 2.0 # Initial guess for square root of 4 while error > tolerance: new_x = 0.5 * (x + 4/x) # Newton's method error = abs(new_x - x) x = new_x print(f"Current estimate: {x:.6f}, Error: {error:.6f}") print(f"\nFinal square root approximation: {x:.6f}")
6. Common Mistakes
- - Forgetting to update the variable in the condition (causes infinite loop)
- - Using == instead of = when you mean to assign a value
- - Over-complicating conditions that could be simpler
7. While vs For Loops
While Loop | For Loop |
---|---|
Use when you don't know how many iterations are needed | Use when you know how many times to repeat |
Runs until condition is false | Runs for each item in a sequence |
Risk of infinite loops | No risk of infinite loops |
8. Advanced Techniques
- - While-else: The else block executes when the condition becomes false
- - Nested while loops: While loops inside other while loops
- - Flag variables: Using boolean variables to control loop execution
Python Loop Manipulation: pass, continue, break, and else
Introduction to Loop Control Statements
These statements help you control the flow of loops in Python. They work with both for
and while
loops.
The pass
Statement
This is a null operation - nothing happens when it executes.
When to use: When you need a statement for syntax purposes but don't want any action.
for i in range(5): if i == 3: pass # Do nothing print(i) # Output: 0 1 2 3 4
Engineering Example: Placeholder for future sensor reading implementation
while True: sensor_reading = get_sensor_data() if sensor_reading < 0: pass # Will implement error handling later else: process_data(sensor_reading)
The continue
Statement
Skips the rest of the current loop iteration and moves to the next one.
for i in range(1, 6): if i % 2 == 0: continue # Skip even numbers print(f"Processing odd number: {i}") # Output: Processing odd number: 1, 3, 5
Engineering Example: Skip invalid measurements
measurements = [12.5, -1, 15.2, 0, 18.7] for m in measurements: if m <= 0: continue # Skip invalid measurements analyze_measurement(m)
The break
Statement
Exits the loop completely, skipping all remaining iterations.
for i in range(10): if i == 5: break # Exit loop when i reaches 5 print(i) # Output: 0 1 2 3 4
Engineering Example: Emergency shutdown when critical threshold reached
while True: temperature = get_temperature() if temperature > 100: print("Critical temperature reached! Shutting down.") break process_temperature(temperature)
The else
Clause in Loops
Executes only if the loop completes normally (not terminated by break).
for i in range(5): if i == 10: break print(i) else: print("Loop completed normally") # Output: 0 1 2 3 4 # Loop completed normally
Engineering Example: Check if all tests passed
test_results = [True, True, True, True] for result in test_results: if not result: print("Test failed! Stopping.") break else: print("All tests passed successfully!")
Comparison Table
Statement | Effect | When to Use |
---|---|---|
pass |
Does nothing | Placeholder for future code |
continue |
Skips current iteration | When you want to skip specific items |
break |
Exits the loop completely | When you need to stop processing |
else |
Runs after normal completion | For post-loop checks |
Combined Example
# Process engineering data with all control statements data = [2.5, 3.8, -1, 4.2, 0, 5.1, 6.7, 999] for value in data: if value == 999: # Sentinel value print("Termination signal received") break elif value <= 0: print(f"Invalid value {value} skipped") continue elif value > 5: pass # Will handle high values later else: print(f"Processing normal value: {value}") else: print("All data processed normally") print("Data processing complete")
Programming Using Python Conditional and Loop Blocks
Introduction to Control Structures
Control structures help you control the flow of your program's execution. There are two main types:
- - Conditional blocks (if, elif, else) - for decision making
- - Loop blocks (for, while) - for repeating actions
Conditional Blocks
a) if statement
temperature = 85 if temperature > 100: print("System overheating!")
This checks if temperature exceeds 100 and prints a warning if true.
b) if-else statement
voltage = 220 if voltage >= 200 and voltage <= 240: print("Voltage within normal range") else: print("Voltage out of range!")
This checks voltage and provides different outputs for normal and abnormal conditions.
c) if-elif-else ladder
rpm = 3500 if rpm > 5000: print("Danger! Critical speed") elif rpm > 4000: print("Warning! High speed") elif rpm > 3000: print("Approaching limit") else: print("Normal operating range")
This checks multiple conditions in sequence.
Loop Blocks
a) for loop
# Calculate sum of resistances in a circuit resistances = [10, 20, 30, 40] total = 0 for r in resistances: total += r print(f"Total resistance: {total} ohms")
b) while loop
# Countdown timer time_left = 10 while time_left > 0: print(f"Countdown: {time_left}") time_left -= 1 print("Launch!")
Combining Conditionals and Loops
Example 1: Data Validation
measurements = [12.5, -1, 15.2, 0, 18.7] valid_readings = 0 for m in measurements: if m <= 0: print(f"Invalid reading: {m}") continue valid_readings += 1 print(f"Processing valid reading: {m}") print(f"Total valid readings: {valid_readings}")
Example 2: Finding Prime Numbers
# Check if a number is prime num = 17 is_prime = True for i in range(2, num): if num % i == 0: is_prime = False break if is_prime and num > 1: print(f"{num} is a prime number") else: print(f"{num} is not a prime number")
Nested Control Structures
# Temperature monitoring system temperatures = [85, 92, 78, 105, 88] critical_count = 0 for temp in temperatures: if temp > 90: print(f"High temperature alert: {temp}°C") if temp > 100: critical_count += 1 print("CRITICAL! Immediate action required") else: print(f"Normal temperature: {temp}°C") print(f"Total critical alerts: {critical_count}")
Practical Engineering Applications
- - Sensor data processing: Filter valid/invalid readings
- - System monitoring: Check multiple parameters continuously
- - Simulations: Repeat calculations until convergence
- - Control systems: Implement decision logic for actuators
- - Data analysis: Process large datasets with conditional checks
Best Practices
- - Keep conditions simple and readable
- Avoid deeply nested structures (more than 3 levels)
- - Use meaningful variable names in conditions
- - Add comments for complex conditions
- - Test edge cases in your conditions
- - Ensure loops have clear termination conditions
Common Mistakes to Avoid
- - Forgetting colons (:) after conditions and loops
- - Missing indentation for blocks
- - Creating infinite loops (while True without break)
- - Using = (assignment) instead of == (comparison)
- - Not updating variables used in loop conditions
No comments:
Post a Comment