Control Flow and Data Structures¶
Once you can assign values and write functions, the next step is telling Python how to make decisions, repeat work, and organize collections of data.
Conditionals¶
Use conditionals when your program should behave differently depending on a value:
temperature = 18
if temperature < 0:
print("Freezing")
elif temperature < 20:
print("Cool")
else:
print("Warm")
This pattern appears everywhere: validating inputs, checking files, handling errors, and controlling workflow.
Lists, tuples, dictionaries, and sets¶
Python has several built-in data structures, each with a different purpose.
Lists¶
Lists store ordered, changeable collections:
Tuples¶
Tuples also store ordered values, but they are typically used for fixed groups of values:
Dictionaries¶
Dictionaries map keys to values:
They are useful whenever labels matter as much as the values themselves.
Sets¶
Sets store unique values and are useful for quick membership tests:
Loops¶
Loops let you repeat an operation.
for loops¶
Use for when iterating over a sequence:
while loops¶
Use while when repetition depends on a condition:
List comprehensions¶
List comprehensions are a compact way to build a list from another iterable:
They are powerful, but clarity still matters. If a comprehension becomes hard to read, a normal loop is often the better choice.
Error and exception handling¶
Real code should fail in understandable ways. A basic try / except
structure helps:
Use exception handling to react to expected failure modes, such as invalid input, missing files, or parsing problems.
Recursion¶
Recursion means a function calls itself. It is useful for some problems, but it is not always the clearest choice for beginners:
It is worth understanding the idea, even if loops remain the more common tool in daily work.
Practice ideas¶
- Create a list of numbers and print only the even ones.
- Build a dictionary that stores a few measurements by name.
- Write an
if/elif/elseblock for a grading scale. - Convert a
forloop into a list comprehension and compare readability.