What Will You Learn?

  • What are the basics of Python?
  • What are the use cases for Python?
  • How can I install Python?
  • How can I create a virtual environment?
  • How can I install packages?
  • What are the fundamentals of Python?
  • Where can I learn more about Python?

This article assumes a working knowledge of the command line.

The Basics

Python is an object-oriented, interpreted, and easy-to-learn programming language. The syntax is concise and approachable to beginners. Python is a popular language for data analysis, machine learning, and web development. It was created by Guido van Rossum and first released in 1991.

Primary Use Cases

Python is best known for its use in data analysis and machine learning with libraries like the Pandas library and TensorFlow. Python is also a popular language for server-side web development with libraries like Django and more recently became viable directly in the browser with PyScript using Web Assembly. Python is a general-purpose language, so it’s also suitable for use cases like scripting, automation, and command-line tools.

Uncommon and Unsuitable Use Cases

While it’s possible to use Python for mobile development with libraries like Kivy, desktop development with libraries like PyQt, and game development with libraries like PyGame, it’s an uncommon choice. Python is unsuitable for low-level programming like operating systems and embedded systems. However, it’s possible to use runtimes like CPython and MicroPython to get down and dirty.

Programming Construct Fundamentals

Learn Python without considering the fundamental programming constructs of Python? That’s crazy talk!

Let’s review the basic programming constructs of Python.

Variables

The Variable assignment is simple; there is no magic here, how I like it.

class color:
   BOLD_UNDERLINE = '\033[1m\033[4m'
   END = '\033[0m'

print(color.BOLD_UNDERLINE + 'Assign a string value to a variable' + color.END)
print("\n")
office_name = "Office A"
print(office_name)
print("\n")
print("----------------------------------------------")

print(color.BOLD_UNDERLINE + 'Assign a multiple line string value to a variable' + color.END)
print("\n")
office_name = """Office A\n
Office B
"""
print(office_name)
print("\n")
print("----------------------------------------------")

print(color.BOLD_UNDERLINE + 'Assign an integer value to a variable' + color.END)
print("\n")
office_sales = 7
office_sales_type = type(office_sales)
print(f"office_sales is type: {office_sales_type}")
print("\n")
print("----------------------------------------------")


print(color.BOLD_UNDERLINE + 'Assign a floating point value to a variable' + color.END)
print("\n")
office_score = 7.5
office_score_type = type(office_score)
print(f"office_score is type: {office_score_type}")
print("\n")
print("----------------------------------------------")

print(color.BOLD_UNDERLINE + 'Assign an boolean value to a variable' + color.END)
print("\n")
office_is_active = bool(True)
office_is_active_type = type(office_is_active)
print(f"office_is_active is type: {office_is_active_type}")
print("\n")
print("----------------------------------------------")

"""
Interesting tidbits

Python employs a concept called name mangling for private variables.abs
"""

The code follows the naming section of Google’s style guide. I am using code in the style guide source code as an example. Snake case variable naming is typical when looking at Python code.

Comments

Comments for sanity. Tell your future self and your friends why you did something weird once.

# A simple single-line comment
print("There's a comment before this line, trust me.")
"""
A
Comment
on multiple lines
"""
print("\n")
print("A few comments just happened, honest!")

Control Structures

We saw a for loop in our CSV analysis program.

offices = ["Office A", "Office B", "Office C"]

for office in offices:
  print(office)

Here’s another example.

A while loop

offices = ['Office A', 'Office B', 'Office C']
while offices:
  print(offices.pop(-1))

An if-else statement

office_a_sales = 3
office_b_sales = 100
if office_b_sales > office_a_sales:
  print("Office B sales are greater than Office A sales")
elif office_a_sales > office_b_sales:
  print("Office A sales are greater than Office B sales")

Functions

Functions are the bread and butter of any programming language. I also threw in an f-string, which allows you to format your strings with variables elegantly.

def file_check(fn):
  try:
      example_csv = open("example.csv", "r")
      try:
          print("Found file, printing file")
          print("\n")
          print(example_csv.read())
      finally:
          example_csv.close()
  except IOError:
      print('Error: File does not exist.')

file_check("example.csv")

Save this content to example.csv to run.

store|sales
"Office A","7"
"Office B","3"
"Office C","9"
"Office D","100"
"Office E","4"
"Office F","96"
"Office G","56"
"Office H","34"
"Office I","37"
"Office J","7"

Classes and Objects

Classes and objects are the nuts and bolts.

class Office:
    def __init__(self, name, location, sales):
        self.name = name
        self.location = location
        self.sales = sales

office = Office("Office A", "Portland, Oregon", 7)

print("Office Object Properties:")
print("\n")
print(f"Name: {office.name}")
print(f"Location: {office.location}")
print(f"Sales: {office.sales}")

Lambdas

Lambdas smooth out the rough edges. Use them sparingly; most Python programmers are not a fan of them. Consider using a function rather than a lambda in more complex situations.

offices = [{'name': 'Office A', 'sales': 7},
          {'name': 'Office B', 'sales': 3},
          {'name': 'Office C', 'sales': 9}]

print("Get the office with the highest amount of sales")
print(max(offices, key=lambda x: x['sales']))
print("\n")

print("Get the office with the least amount of sales")
print(min(offices, key=lambda x: x['sales']))

Exception Handling

Exception handling to keep from angering the user gods. Keep your errors under control and handle the flow.

def read_file(file_name):
    example_csv = None
    try:
        example_csv = open(file_name, "r")
    except IOError:
        print("Error: File does not exist.")
    return example_csv

example_csv = read_file("example_missing.csv")

Arrays

Arrays for life. Python arrays don’t contain surprises, making them easy to use.

offices = ["Office A","Office B", "Office C"]

print(f"We have an office array: {offices}")
print("\n")

print("Accessing array item 0")
x = offices
print(f"Found {x}")
print("\n")

print("Update an array value")
offices[0] = "Office Z"
print(f"Updated Office A to {offices[0]}")
print("\n")

print("Get the length of an array")
x = len(offices)
print(f"{x} offices exist in the array")

print("\n")
print("Loop a sorted array")
for x in sorted(offices):
 print(x)
print("\n")

print("Add an array element named Office Y")
offices.append("Office Y")
print(offices)
print("\n")

print("Remove an array element")
offices.pop(1)
print(offices)
print("\n")

print("Delete an array element")
offices.remove("Office C")
print(offices)
print("\n")

Operators

Operators for operating stuff.

class color:
   BOLD = '\033[1;37;48m'
   CYAN = '\033[1;36;48m'
   YELLOW = '\033[1;33;48m'
   BOLD_YELLOW = BOLD + YELLOW
   BOLD_CYAN = BOLD + CYAN
   END = '\033[1;37;0m'

print(color.BOLD_CYAN + "Arithmetic Operators" + color.END)
print("\n")

addition = 1 + 1
print(f"1 + 1 = {addition}")
print("\n")

subtraction = 2 - 1
print(f"2 - 1 = {subtraction}")
print("\n")

multiplication = 3 * 3
print(f"3 * 3 = {multiplication}")
print("\n")

division = 10 / 5
print(f"10 / 5 = {division}")
print("\n")

modulus = 6 % 3
print(f"6 % 3 = {modulus} ")
print("\n")

exponentiation = 2 ** 3
print(f"2 ** 3 = {exponentiation}")
print("\n")

print(color.BOLD_YELLOW + "Assignment Operators" + color.END)
print("\n")

equals = 1
print(f"1 = {equals}")

equals += 1
print(f"1 += {equals}")

minus_equals = 2
minus_equals -= 1
print(f"2 -= {minus_equals}")

multiply_and = 5
multiply_and *= 5
print(f"5 *= {multiply_and}")

divide_and = 5
divide_and /= 5
print(f"5 /= {divide_and}")

modulus_and = 6
modulus_and %= 3
print(f"6 %= {modulus_and}")

exponent_and = 2
exponent_and *= 3
print(f"2 *= {exponent_and}")

y = 7
floor_division = 78125.0
floor_division//=y
print(f"7 //= {floor_division}")

Most Python operators are standard, but watch out for type comparisons. Type comparisons with operators will compare the type names rather than the types themselves. Use the isInstance built-in function to compare types instead.

There are many other constructs to learn in Python. Thanks to its natural and straightforward behavior, it’s a joy to work with Python.

Virtual Environments

If you like your hair, virtual environments are necessary for Python development. They’re isolated environments that allow us to manage project-specific dependencies and use different versions of Python tightly.

You’ll need to install Python to follow along.

Create a virtual environment with the venv package, or pick another package based on your needs.

python3 -m venv venv/

Note: You may run into issues running this on a network drive. If the command hangs, try moving your folder to a physical disk.

Run this command to activate the environment.

source venv/bin/activate

You should see a shell prompt similar to this if successful. Note the (env) text indicating that the virtual environment is activated.

(venv) Jeffs-Laptop:python jeffbailey$

Now, your program is isolated from the system.

To leave the virtual environment, run this command in your directory.

deactivate

Install Required Packages

Now that we have a virtual environment, we can install the Pandas package, but this time in the virtual environment.

pip install pandas

We can run this nifty command to create a requirements.txt file. This file tells users of our program what package versions to use.

pip freeze > requirements.txt

The freeze command will create a file that contains the dependencies you’ll need to run the analyze-csv.py file. Run this command to view the contents.

cat requirements.txt

You should see an output like this.

$ cat requirements.txt
numpy==1.18.4
pandas==1.0.3
python-dateutil==2.8.1
pytz==2020.1
six==1.15.0

the pip freeze command lists all packages installed on your system. We’ve now defined which dependencies are required for the program to run. Users of your application can run this command to install the necessary modules.

pip install -r requirements.txt

The virtual environment will keep us from using our system-wide installation of Python, which may have issues.

Here’s An Example Program That Chunks CSV Files

Now that we’ve reviewed the basics let’s create a program that chunks CSV files. This program will read a CSV file and print the contents in chunks. This program will be helpful for large CSV files.

Download these files to run the code above and put them in the same directory.

example.csv & analyze-csv.py & .gitignore

Here’s the code for the analyze-csv.py file.

#!/usr/bin/env python3
import pandas as pd

filename = "example.csv"
print(f"Chunking records for {filename}")
print("\n")
chunksize = 3
for chunk in pd.read_csv(filename, chunksize=chunksize):
    print(chunk)

Running this code requires a little more work.

Create a virtual environment.

python3 -m venv venv/

Now install pip to install the Pandas library for data analysis tasks.

python3 -m pip install --user --upgrade pip

Install the Pandas package.

pip3 install pandas

Run this command in your terminal to make the program executable.

chmod +x ./analyze-csv.py

Run this command to list all your files.

ls -w

You should see output like this.

$ ls -w
analyze-csv.py  example.csv

Now execute the file.

./analyze-csv.py

You should see the following output.

$ ./analyze-csv.py
          store|sales
Office A            7
Office B            3
Office C            9
          store|sales
Office D          100
Office E            4
Office F           96
          store|sales
Office G           56
Office H           34
Office I           37
          store|sales

Low effort is needed to create a CSV file chunking program.

Show Me The Bits

Run this command to clone the Python folder in my repository on GitHub.

git clone git@github.com:jeffabailey/learn.git --single-branch programming/python && cd programming/python

Learn Python Beyond the Basics

There are thousands of Python books and loads of free tutorials online. Here are a couple of noteworthy titles that will help you learn effectively. I’ll leave you with The Zen of Python.

Books 📚

Videos 📺