2 - Control Flow and Python Data Structures — Topics & Learning Outcomes
Module Topics
Conditional Statements
Conditional statements allow a program to make decisions by executing different code blocks based on whether a condition evaluates to true or false. This topic covers if, elif, and else constructs in Python.
- The if Statement — The if statement is the most fundamental conditional construct in Python, executing a block of code only when a specified condition is True.
- The elif Clause — The elif (else-if) clause allows a program to check multiple conditions in sequence after an initial if condition fails.
- The else Clause — The else clause defines a default block of code that executes when none of the preceding if or elif conditions are True.
- Comparison and Logical Operators — Conditions in Python are built using comparison operators (==, !=, <, >, <=, >=) and logical operators (and, or, not) to form complex Boolean expressions.
- Nested Conditionals — Conditional statements can be placed inside other conditional blocks to test additional conditions when an outer condition is True.
for Loops and the range() Function
The for loop iterates over a sequence of items, making it ideal for processing collections of data. The range() function generates numeric sequences commonly used to control loop iterations.
- The for Loop — A for loop in Python iterates over each item in a sequence — such as a list, string, or range — executing the loop body once per item.
- The range() Function — The range() function generates an immutable sequence of integers and is commonly used with for loops to repeat an action a specific number of times.
- Iterating with an Index Using enumerate() — The enumerate() function allows a for loop to access both the index and the value of each item in an iterable simultaneously.
- Looping Over Numeric Ranges in Engineering — Engineering applications frequently require iterating over a defined numeric range, such as time steps in a simulation or indices in a data array.
while Loops
A while loop repeats a block of code for as long as a specified condition remains True, making it suitable for situations where the number of iterations is not known in advance.
- The while Loop Structure — A while loop continuously executes its body until its controlling condition evaluates to False, checking the condition before each iteration.
- Infinite Loops and Loop Guards — An infinite loop occurs when a while loop's condition never becomes False, causing the program to run indefinitely without halting.
- Comparing for and while Loops — Choosing between a for loop and a while loop depends on whether the number of iterations is known in advance or determined dynamically during execution.
Loop Control: break and continue
The break and continue statements provide fine-grained control over loop execution, allowing early termination or skipping specific iterations without exiting the loop entirely.
- The break Statement — The break statement immediately terminates the innermost loop it appears in, transferring control to the first statement after the loop.
- The continue Statement — The continue statement skips the remainder of the current loop iteration and jumps directly to the next iteration's condition check.
- The else Clause on Loops — Python allows an optional else clause on both for and while loops, which executes only if the loop completed normally without encountering a break statement.
- Practical Use Cases for break and continue — In engineering and data processing, break and continue are frequently used to handle exceptions in data, implement early-exit optimizations, and process conditional sequences.
Lists
Lists are ordered, mutable sequences that can hold items of any type, making them one of the most versatile and widely used data structures in Python.
- Creating and Accessing Lists — A list is created using square brackets and can store any mix of data types. Individual elements are accessed using zero-based integer indices.
- Modifying Lists — Because lists are mutable, their elements can be changed, added, or removed after the list is created using built-in methods and direct assignment.
- List Slicing — Slicing extracts a sub-list from a list using the syntax list[start:stop:step], returning a new list containing the selected elements.
- List Comprehensions — A list comprehension provides a concise, readable way to create a new list by applying an expression to each item in an iterable, optionally filtered by a condition.
- Common List Operations and Methods — Python provides a rich set of built-in functions and list methods for sorting, searching, counting, and transforming list data.
Tuples
Tuples are ordered, immutable sequences that are ideal for storing fixed collections of data that should not be changed after creation.
- Creating and Accessing Tuples — Tuples are defined using parentheses (or simply commas) and support the same indexing and slicing operations as lists, but their contents cannot be modified.
- Immutability of Tuples — Once a tuple is created, its elements cannot be added, removed, or changed, making tuples a safer choice when data integrity is important.
- Tuple Packing and Unpacking — Tuple packing assigns multiple values into a single tuple, while tuple unpacking assigns the elements of a tuple to individual variables in one statement.
- When to Use Tuples vs. Lists — Tuples are preferred when the data represents a fixed record or should be protected from modification, while lists are better suited for collections that need to grow or change.
Dictionaries
Dictionaries store data as key-value pairs, enabling fast lookups by key rather than by position, and are ideal for representing structured, labeled data.
- Creating and Accessing Dictionaries — Dictionaries are created using curly braces with colon-separated key-value pairs. Values are retrieved by supplying the corresponding key in square brackets.
- Modifying Dictionaries — Dictionaries are mutable; entries can be added, updated, or deleted at any time using direct assignment and built-in methods.
- Iterating Over Dictionaries — Python provides dedicated methods for iterating over a dictionary's keys, values, or key-value pairs using keys(), values(), and items().
- Engineering Applications of Dictionaries — Dictionaries are well suited for mapping labeled engineering data, such as material properties, configuration parameters, or named measurement channels.
Sets and Choosing the Right Data Structure
Sets store unique, unordered elements and support efficient membership testing and set operations. This topic also provides guidance on selecting the appropriate data structure for engineering problems.
- Creating and Using Sets — A set is an unordered collection of unique elements defined with curly braces or the set() constructor. It automatically discards duplicate values.
- Set Operations — Sets support mathematical operations including union, intersection, difference, and symmetric difference, enabling powerful comparisons between groups of data.
- Membership Testing with Sets — Sets provide O(1) average-time membership testing using the in operator, making them significantly faster than lists for checking whether a value exists in a large collection.
- Comparing Core Data Structures — Lists, tuples, dictionaries, and sets each have distinct properties — ordered vs. unordered, mutable vs. immutable, indexed vs. keyed — that make them appropriate for different tasks.
- Selecting the Right Structure for Engineering Problems — Choosing the appropriate data structure improves program correctness, performance, and readability, particularly in data-intensive engineering applications.
Student Learning Outcomes
By the end of this module, students will be able to:
MO1
Construct conditional statements using if, elif, and else clauses — combined with comparison and logical operators — to control program execution flow
Level: ApplyType: CognitiveCourse mapping: CO3
MO2
Implement for loops, while loops, and loop control statements (break and continue) to iterate over sequences and numeric ranges in engineering contexts
Level: ApplyType: CognitiveCourse mapping: CO3
MO3
Manipulate Python lists using indexing, slicing, list comprehensions, and built-in methods to process ordered collections of data
Level: ApplyType: CognitiveCourse mapping: CO1
MO4
Differentiate between lists, tuples, dictionaries, and sets based on their properties of mutability, ordering, and access method
Level: AnalyzeType: CognitiveCourse mapping: CO1
MO5
Select the appropriate Python data structure for a given engineering problem by evaluating the correctness, performance, and readability trade-offs among lists, tuples, dictionaries, and sets
Level: EvaluateType: CognitiveCourse mapping: CO1
Course Outcomes (reference)
CO1Use variables, arrays and object structures appropriate to solve engineering problems.
CO2Write computer functions to meet specific calculation needs.
CO3Write computer programs to solve mathematical expressions and engineering problems