Get Started with Python - Part 3
This is the third part of the Jump In guide introducing core Python concepts in a hands-on way. This page covers iteration and flow controls. Looping and logic determine what code runs and when. Mastering this will help avoid repetitive code and handle multiple use-cases. Be sure to check out the accompanying notebook for more experience.
NOTE: By design, Python does not return anything when a variable is assigned. So example cells here, where only variable assignment happens, will run without generating output. The variable is still saved in the runtime and can be accessed in following cells once it is set.
DRY, a principle of software engineering, reminds developers to avoid duplicative or repetitive code. Having multiple code sections that are nearly identical is a pain to maintain. If you ever find yourself having to edit code in multiple places for a single change, consider if there is a better approach. Iteration and flow control are core ways to ensure DRY code.
Iteration
Many datatypes allow for iteration. This section will focus on lists, strings, ranges, and dictionaries as examples. Iteration repeatedly executes a block of code.
Lists
List iteration is incredibly powerful. The cells below first create a list, then iterates over it.
Strings
Stings in Python are iterable. See the below to iterate over characters.
Nested Loops
Loops can be nested.
Ranges
Range can be used to execute code a given number of times. Usage is range(start, stop, step), where stop is required and start and step are optional. Stop is exclusive, meaning that number is not part of the sequence. Examples below help illustrate. NOTE: Python is a 0 based indexing system.
Enumerate
Enumerate is a built-in function to add a counter to iteratable objects like lists.
Dictionaries
Dictionaries hold mapped key-value pairs. They are iterable, but must be handled differently than lists. keys will iterate over the keys, while values iterates over the values, and items iterates over both.
Dictionary Lookup
Dictionary mapping is usefulf in many contexts. The key of a dictionary can be used to lookup the corresponding value.
Syntax: dict[key].
Flow Control
By default, code is executed from the top to bottom of a script. Flow control is used for more advanced execution that may include repeating blocks, skipping conditions, early exits, and error handling. The ‘if-elif-else’ conditional statement is the most commonly used method of flow control in Python.
When combined with iteration and DRY, very little code can have very impactful results.
If-Elif-Else
The most commonly used flow control in Python. Run the cells below and edit to make x the magic number.