[Python] Introduction to Python Programming

This post covers Python fundamentals: variables, data types, collections, loops, and functions. These are the basics you need before moving on to pandas, the library that most data analysis in Python runs through.

Python for Data Analysis

Python has become the standard language for data analysis across disciplines. Unlike paid software like SPSS or Excel, Python is free, open-source, and supported by a large community. More importantly, it integrates well with AI tools like ChatGPT and Claude, which can help you write and debug code as you learn.

Your First Python Program

Programming tutorials traditionally start with “Hello World.” This tradition dates back to the 1970s, and it’s basically a programmer’s way of saying “I exist!” to the computer 🙂

Open a Python environment (IDLE, Jupyter Notebook, or Google Colab) and type:

Python
print("Hello World")

When you run this, you’ll see:

Hello World

The print() function displays text or data on your screen. It is a simple command, but you will use it constantly to check what your code is doing.

Variables

Variables let you store data for later use: you put a value somewhere and give it a name so you can retrieve it later. In most programming languages, a single equal sign (=) means that you are “assigning” something.

Python
name = "Maria" # You assign Maria to name variable 
age = 28 # You assign value 28 to age variable
is_student = True # You assign True value to is_student variable

Here, name stores text, age stores a number, and is_student stores a true/false value. The = sign does not mean “equals” the way it does in math. It means “assign this value to this variable,” so what is on the right gets stored under the name on the left.

You can use these variables throughout your code:

Python
print(name)  # Output: Maria
print(age)   # Output: 28

Variable names should be descriptive. Instead of x, use client_age or survey_response. You will be reading this code again a month later, and descriptive names are what make that possible.

Data Types

Python has several basic data types, and you will use all of them when working with data.

Strings (Text)

Strings represent text and are enclosed in quotes, either “” or ”:

Python
first_name = "John"
last_name = 'Doe'

You can combine strings using + (concatenation):

Python
full_name = first_name + " " + last_name
print(full_name)  # Output: John Doe

You can also count the number of character of string variable and make it into upper or lower case:

Python
message = "Hello, world!"
print(len(message))        # Length: 13
print(message.upper())     # HELLO, WORLD!
print(message.lower())     # hello, world!

Numbers

Python has two main numeric types:

Python
# Integers (whole numbers)
num_clients = 45
year = 2024

# Floats (decimal numbers)
average_score = 3.7
percentage = 85.5

You can perform mathematical operations. Simply you are using it as a calculator:

Python
total = 100
completed = 67
completion_rate = (completed / total) * 100
print(completion_rate)  # Output: 67.0

Booleans (True/False)

Booleans represent binary states (yes/no):

Python
is_active = True
has_insurance = False
meets_criteria = age >= 18 and is_active

These are particularly useful for filtering data and conditional logic.

Collections

Real-world data rarely comes as single values. Python provides several ways to store collections of data.

Lists

Lists are ordered collections that can hold multiple items:

Python
client_ages = [25, 34, 42, 28, 51]
service_types = ["counseling", "housing", "employment", "healthcare"]

You can access items by their position (starting from 0):

Python
print(client_ages[0])      # First item: 25
print(service_types[2])    # Third item: employment

Why does the first item have index 0? Python counts positions from 0, the same convention as ground-floor numbering in many countries, where the floor at street level is 0 and the next one up is 1.

Lists are mutable, meaning you can change them after creating them:

Python
client_ages.append(39)     # Add a new age
print(client_ages)         # [25, 34, 42, 28, 51, 39]

service_types[1] = "food assistance"
print(service_types)       # ['counseling', 'food assistance', 'employment', 'healthcare']

This matters for data cleaning, where you often add or replace entries as you go.

Dictionaries

Dictionaries store data as key-value pairs. The name comes from actual dictionaries: you look up a word (the key) to find its definition (the value).

Python
client = {
    "id": 1001,
    "name": "Sarah Johnson",
    "age": 32,
    "services": ["counseling", "housing"]
}

print(client["name"])      # Sarah Johnson
print(client["age"])       # 32

With a dictionary you do not have to remember that the client’s name is the third item. You ask for client["name"] and you get it, which is easier to keep track of than the numeric positions lists use.

Dictionaries are how structured data is usually represented, whether that is client records, survey responses, or program information. Most real-world data you will work with, including JSON from APIs and database records, uses this key-value structure.

Basic Operations and Control Flow

Conditional Statements

Conditional statements let your code make decisions:

Python
age = 17

if age >= 18:
    print("Adult services available")
else:
    print("Youth services available")

You can check multiple conditions:

Python
income = 25000

if income < 20000:
    eligibility = "Full subsidy"
elif income < 40000:
    eligibility = "Partial subsidy"
else:
    eligibility = "No subsidy"

print(eligibility)

Loops

Loops let you repeat an operation across many records. With 500 client records that each need the same calculation, you either copy-paste the code 500 times or write a loop.

For loops iterate over collections:

Python
ages = [23, 45, 34, 56, 28]

for age in ages:
    print(f"Client age: {age}")

The loop says “for each client in my caseload, do this thing.” The computer runs it instantly instead of you doing it one by one.

You can calculate statistics:

Python
ages = [23, 45, 34, 56, 28]
total = 0

for age in ages:
    total = total + age

average = total / len(ages)
print(f"Average age: {average}")  # Average age: 37.2

Without a loop, you’d have to write total = 23 + 45 + 34 + 56 + 28. Now consider doing that for 500 numbers. The loop handles the repetitive part so you can spend your time on analysis and interpretation.

While loops continue until a condition is met:

Python
count = 0
while count < 5:
    print(f"Count: {count}")
    count = count + 1

While loops are useful when you do not know in advance how many repetitions you need, as in “keep asking for input until the user enters a valid response.”

Functions

Functions let you package code for reuse. Instead of writing the same code repeatedly, you define a function once and call it whenever needed:

Python
def calculate_risk_score(has_housing, has_income, has_support):
    score = 0

    if not has_housing:
        score += 3
    if not has_income:
        score += 2
    if not has_support:
        score += 2

    return score

# Use the function
client_risk = calculate_risk_score(False, True, False)
print(f"Risk score: {client_risk}")

Functions make your code organized and easier to maintain.

Python Quirks and Conventions

Before the full example, here are some Python-specific behaviors that are not really “concepts” but will trip you up if you do not know about them.

Indentation

In Python, indentation is part of the syntax.

Python
# This works:
if age >= 18:
    print("Adult")
    print("Can vote")

# This causes an error:
if age >= 18:
print("Adult")  # IndentationError!

Python uses indentation to define code blocks. Most people use 4 spaces per indentation level.

The Great Tab vs Space Debate: Some people use tabs, some use spaces. Python doesn’t care which you pick, but you CANNOT mix them in the same file. Pick one and stick with it. Most style guides recommend spaces (4 of them), and most modern editors can convert tabs to spaces automatically. This debate is so iconic among programmers 🙂

Case Sensitivity

Python treats Name, name, and NAME as three completely different variables.

Python
client_name = "Maria"
Client_name = "John"
CLIENT_NAME = "Sarah"

print(client_name)    # Maria
print(Client_name)    # John
print(CLIENT_NAME)    # Sarah

This seems obvious, but it will catch you while debugging, when Age is not working because what you defined was age.

Naming Conventions

Python has a preferred naming style for variables and functions called “snake_case,” which is all lowercase with underscores between words:

Python
# Good Python style
client_age = 28
total_income = 45000
calculate_risk_score()

# Bad style (works, but not Pythonic)
ClientAge = 28
totalIncome = 45000
CalculateRiskScore()

The latter styles (PascalCase and camelCase) are used in other languages like Java or JavaScript. Python uses them only for class names, which you’ll learn later. Following these conventions makes your code look “Pythonic” and helps other Python programmers read your code.

Comments

Comments are notes in your code that Python ignores. They start with #:

Python
# This is a comment
age = 28  # You can also put comments at the end of lines

# Comments are for explaining WHY, not WHAT
# Bad comment:
total = total + 1  # Add 1 to total

# Good comment:
total = total + 1  # Increment counter for each completed session

Write comments as notes for whoever reads your code in six months, which is usually you. Comments are also useful for temporarily “turning off” code without deleting it:

Python
# print("Debug message")  # Commented out for now

Reading Error Messages

Error messages look scary but they’re actually trying to help. When you get an error, read from bottom to top:

Python
Traceback (most recent call last):
  File "script.py", line 10, in <module>
    result = calculate_score(age, income)
  File "script.py", line 5, in calculate_score
    return score / count
ZeroDivisionError: division by zero

The last line tells you what went wrong (ZeroDivisionError). The lines above tell you where: line 5, inside the calculate_score function.

Common errors you’ll see:

  • SyntaxError: You wrote something Python doesn’t understand (missing colon, wrong indentation)
  • NameError: You tried to use a variable that doesn’t exist (typo?)
  • TypeError: You tried to do something with the wrong data type (like adding a number to a string)
  • IndentationError: Your spacing is inconsistent

Checking Data Types

Python tries to be helpful and will often “guess” what you mean. But sometimes it guesses wrong:

Python
# Python allows this (implicit conversion):
result = "Client " + str(123)  # "Client 123"

# But this will error:
result = "Client " + 123  # TypeError: can only concatenate str to str

When something isn’t working, check your data types. Use type() to see what you’re actually working with:

Python
age = "28"  # Wait, is this a string or a number?
print(type(age))  # <class 'str'> - it's a string!

A Simple Example

Here’s a practical example that combines what we’ve covered:

Python
# Client data
clients = [
    {"name": "Alice", "age": 28, "income": 18000},
    {"name": "Bob", "age": 45, "income": 32000},
    {"name": "Carol", "age": 34, "income": 25000}
]

# Function to determine eligibility
def check_eligibility(income):
    if income < 20000:
        return "Eligible for full assistance"
    elif income < 30000:
        return "Eligible for partial assistance"
    else:
        return "Not eligible"

# Process each client
for client in clients:
    status = check_eligibility(client["income"])
    print(f"{client['name']}, age {client['age']}: {status}")

Output:

Alice, age 28: Eligible for full assistance
Bob, age 45: Not eligible
Carol, age 34: Eligible for partial assistance

Moving Toward pandas

The structures covered here (lists, dictionaries, loops) do the job, but they become cumbersome with large datasets. Managing survey data from 500 respondents with 50 questions each using only basic Python structures would be tedious and error-prone.

This is what pandas is for. It provides a DataFrame structure that handles tabular data efficiently, closer to a spreadsheet that you manipulate with code. Everything covered here (data types, loops, conditionals, functions) still applies, and pandas adds tools specific to data analysis.

The next post introduces pandas, where operations that take dozens of lines of basic Python can be done in one or two.

Resources

  • Official Python Tutorial: https://docs.python.org/3/tutorial/
  • Python for Everybody (free course): https://www.py4e.com/
  • Real Python (tutorials): https://realpython.com/

The next post in this series covers pandas and how it handles real-world datasets.

  • December 22, 2025