Python Crash Course: Part 3


Crash Course Part 1  |  Crash Course Part 2  |  Crash Course Part 3

Introduction

Welcome to the final part of our Python crash course! If you’ve followed along with the first two parts, you’re already equipped with a solid foundation of Python programming basics such as variables, data types, control flow, and functions. It’s been a thrilling journey so far, hasn’t it? Now, it’s time to add more powerful tools to your Python toolkit!

In this concluding part, we’ll delve into essential Python data structures – lists and dictionaries – and the operations you can perform with them. We’ll also briefly touch upon tuples and sets. Lastly, we’ll explore the basics of file handling in Python, a crucial skill when dealing with data storage and retrieval. As always, we’ll include hands-on examples and exercises to help you absorb these concepts better. So, ready to dive in? Let’s start with Python lists!

Lists

Before diving into coding, let’s imagine you’re at a grocery store. You have a shopping list that keeps track of all the items you need to buy. In Python, you can represent such a collection of items using a data structure called a list.

A list in Python is an ordered collection of items. The items in the list can be anything – numbers, strings, other lists, or even different types of data combined.

Creating Lists

Creating a list in Python is as simple as enclosing elements in square brackets [] and separating them with commas.

my_list = ['apple', 'banana', 'cherry']
print(my_list)

Accessing List Elements

Now, suppose you want to retrieve an item from your list. You can do this using indexing. Python indices start from 0 for the first element. So, if you want to access the first item in your list:

first_item = my_list[0]
print(first_item)  # This will print 'apple'

You can also slice lists to access multiple elements at once. The syntax is list[start:end], where the start index is included and the end index is excluded.

slice_of_list = my_list[1:3]  
print(slice_of_list)  # This will print ['banana', 'cherry']

Modifying Lists

Lists in Python are mutable, meaning you can change their contents. To change an element, assign a new value to a specific index.

my_list[1] = 'blueberry'
print(my_list)  # This will print ['apple', 'blueberry', 'cherry']

You can add elements to your list using the append() method or the extend() method, and remove elements using the remove() method or the pop() method.

Iterating Over Lists

To perform operations on each item in a list, you can iterate over it using a for loop.

for item in my_list:
    print(f"I'm buying {item}.")

Dictionaries

Imagine you’re reading a book and using a real-life dictionary to look up the meaning of words. You have a word (the key) and its corresponding meaning (the value). Python provides a dictionary data structure that works in a similar way.

A dictionary in Python is an unordered collection of key-value pairs. Dictionaries are mutable and each key-value pair is separated by a colon.

Creating Dictionaries

You can create a dictionary by enclosing key-value pairs in curly braces {}.

my_dict = {'apple': 1.99, 'banana': 0.99, 'cherry': 2.99}
print(my_dict)

Accessing Dictionary Values

To access a value in the dictionary, you use its corresponding key.

apple_price = my_dict['apple']
print(apple_price)  # This will print 1.99

Modifying Dictionaries

To modify a dictionary, you can add, change, or delete key-value pairs.

my_dict['blueberry'] = 3.99  # Adding a new key-value pair
print(my_dict)  # This will include 'blueberry': 3.99 in the dictionary

my_dict['apple'] = 1.49  # Changing the value of an existing key
print(my_dict)  # The value for 'apple' is now 1.49

del my_dict['banana']  # Deleting a key-value pair
print(my_dict)  # 'banana' and its value are now removed from the dictionary

Iterating Over Dictionaries

You can iterate over a dictionary using a for loop to access its keys and values.

for key, value in my_dict.items():
    print(f"The price of {key} is ${value}.")

Tuples and Sets

Tuples

A tuple is similar to a list, but it is immutable, meaning its contents cannot be changed after creation. It can be used to group related pieces of information.

my_tuple = ('apple', 1.99)
print(my_tuple)  # This will print ('apple', 1.99)

Sets

A set is an unordered collection of unique elements. It’s useful for keeping track of distinct items.

my_set = {'apple', 'banana', 'cherry', 'apple'}
print(my_set)  # This will print {'apple', 'banana', 'cherry'} as sets remove duplicates

File Handling

In Python, you can open files, read their contents, modify them, and close them when you’re done. This is extremely useful for any tasks involving data storage or retrieval.

Opening Files

To open a file, use the open() function, specifying the file path and the mode (‘r’ for read, ‘w’ for write, ‘a’ for append, etc.).

my_file = open('myfile.txt', 'r')

Reading from Files

You can read the entire contents of a file using the read() method.

file_contents = my_file.read()
print(file_contents)

Writing to Files

To write to a file, open it in ‘w’ (write) or ‘a’ (append) mode and use the write() method.

my_file = open('myfile.txt', 'w')
my_file.write("Hello, Python!")

Closing Files

Remember to close your files when you’re done with them. This is important because it frees up system resources.

my_file.close()

Conclusion and Next Steps

Congratulations on completing this Python crash course! In this series, you’ve learned about Python fundamentals like variables, data types, control flow, functions, and data structures.

From here, you can deepen your Python knowledge by exploring advanced topics such as object-oriented programming, libraries, and frameworks. Consider diving into specific areas like web development with Django, data analysis with Pandas, or machine learning with scikit-learn.

Most importantly, practice, practice, practice! The more you code, the more you’ll reinforce your understanding and get comfortable with Python. Good luck on your Python coding journey!