Taming the Python Jungle: Data Structures and Control Flow Statements

akki
𝐀𝐈 𝐦𝐨𝐧𝐤𝐬.𝐢𝐨
5 min readMay 15, 2024

Organizing Your Python Backpack: Exploring Data Structures

Greetings, code adventurers! We’ve been steadily accumulating valuable tools on our Python journey — variables, data types, operators, and now we’re about to delve into a crucial aspect: data structures. Imagine embarking on a real expedition; you wouldn’t throw everything haphazardly into a single backpack. Data structures in Python serve a similar purpose — they provide organized ways to store and manage your data, making your programs more efficient and readable.

The Mighty List: Ordered Collections

Think of a grocery list or a checklist for your adventure — that’s the essence of a list in Python. Lists are ordered collections of items, much like the items in your backpack. These items can be of various data types (numbers, strings, even other lists!). You can access and modify elements based on their position (index) within the list, starting from 0.

Here’s how you create and manipulate lists:

Let’s talk about indexes in a list:
There’s positive and negative indexing. These index numbers are allocated in memory. Below is a visual representation of indexing in lists.

Source — https://www.codingem.com/python-indexing-from-end/

# An example in shopping_list: We can access the very first element as —
first_item = shopping_list[0]

# Another way to access the first item is by using negative indexes
first_item = shopping_list[-4]

Try it out in VS Code, Jupyter Notebook, PyCharm, or any other preferred IDE, and experiment with trying to access different elements in a list using both positive and negative indexes to solidify your understanding.

Lists are incredibly versatile. You can use them to store:

  • Sequences of instructions
  • Sets of travel coordinates
  • Scores in a game

The Marvelous Dictionary: Key-Value Pairs

Imagine a travelogue with entries for different destinations — each entry has a location name (key) and a description (value). This is similar to how dictionaries work in Python. Dictionaries are unordered collections of key-value pairs. Keys must be unique and immutable (like strings or numbers), while values can be of any data type.

Here’s how you create and use dictionaries:

Dictionaries excel at storing:

  • User profiles with usernames and passwords (securely hashed in real applications!)
  • Inventory data with product IDs and descriptions
  • Word definitions in a mini-dictionary program

Choosing the Right Tool: Lists vs. Dictionaries

When should you use a list versus a dictionary? Here’s a general rule of thumb:

  • Use lists when the order of elements matters and you need to access them by position.
  • Use dictionaries when you need to associate unique keys with their corresponding values; fast lookup by key is essential.

Beyond the Basics: Exploring Advanced Data Structures

Lists and dictionaries are the cornerstones, but Python offers a treasure trove of other data structures for specialized tasks:

  • Tuples: Ordered, immutable collections similar to lists, but you can’t modify them after creation (useful for storing constant data).
  • Sets: Unordered collections of unique elements, handy for checking membership or removing duplicates from data.
  • Stacks: LIFO (Last-In-First-Out) principle, like a stack of plates — you can only add/remove elements from the top.
  • Queues: FIFO (First-In-First-Out) principle, like a line at a store — the first element added is the first one removed.

We’ll delve deeper into these advanced data structures in future posts, but for now, grasp the power of lists and dictionaries to organize your data effectively.

Mastering the Python Maze: Control Flow and Loops

It’s time to delve into the exciting realm of control flow statements and loops, the master orchestrators of program execution.

Control Flow Statements: The Decision Makers

Imagine navigating a complex maze. You encounter forks in the path, and you reach different destinations depending on your choices (left or right). Control flow statements in Python function similarly. They allow your program to make decisions and execute specific code blocks based on those decisions.

The cornerstone of control flow is the if statement. It follows this basic structure:

if condition:
# code to be executed if the condition is true
else:
# code to be executed if the condition is false

Here’s an example to check whether the number numis the greater than 100 or not:

Now, what if the input num is 100? Let’s add another condition for when the input number from the user is 100 using elif condition.

elif and Nested Control Flow

The if statement has powerful companions:

  • elif statements: Imagine multiple checkpoints in your maze adventure. You can use a chain of if-elif-else statements to check for various conditions and execute corresponding code blocks.

This program uses nested if-elif statements to provide more granular feedback based on the exam score range.

Loops: The Repeaters for Efficiency

Remember that exhausting climb-up identical ladders in the maze? Loops in Python are your heroes for automating such repetitive tasks. Here are the loop warriors we’ll explore:

  • for loop: Imagine a treasure chest filled with sparkling gems. You want to examine each one. A for loop iterates through a sequence of items (like a list or string) and executes a code block for each item.

This loop iterates through the shopping_list, printing a reminder to buy each item.

  • while loop: Now imagine a secret passage that only opens when a specific phrase is chanted repeatedly. A while loop keeps executing a code block as long as a certain condition remains True.

This loop keeps prompting the user for a guess until they guess the correct secret number.

Challenge Time: Level Up Your Skills

Now that you’ve grasped control flow and loops, let’s put your skills to the test:

  • Simple Text-Based Adventure: Build a basic text-based adventure game using control flow statements. The program can present the user with choices at different points in the story (e.g., “Go left or right?”), and the user’s input determines the path of the adventure. You can incorporate various scenarios, challenges, and outcomes based on the user’s decisions, creating an interactive and engaging experience. The game should have a clear objective or goal for the player to achieve, along with multiple possible endings depending on the choices made throughout the adventure. Have fun creating your text-based adventure game!

Again, to deepen your understanding of data structures and control statements in Python, I would suggest going through chapters 4,6,7, and 8 (check timestamps!) in this tutorial by freecodecamp.

In the next blog, we will learn about functions in Python, and how to leverage modules and libraries in Python. Stay tuned!

P.S. Code blocks do not work at all for me while writing blogs in Medium, I have to use GithubGist and embed code here *sigh*… If you have any trouble copying the code then click on ‘view raw’ and then try to copy the code.

--

--