No history yet

Python Basics

The Building Blocks

Python is known for its clean and readable syntax. It's designed to feel more like plain English than a cryptic computer language. This makes it a great starting point for programming. The first thing you'll work with are variables. Think of them as labeled boxes where you can store information.

message = "Hello, Python!"
print(message)

age = 30
print(age)

In the code above, message is a variable holding text, and age is a variable holding a number. The print() function simply displays the value of the variable. Python automatically figures out the type of data you're storing. These different kinds of information are called data types.

Data TypeDescriptionExample
StringA sequence of characters"apple"
IntegerA whole number100
FloatA number with a decimal point3.14
BooleanRepresents True or FalseTrue

Beyond these simple types, Python has data structures for grouping data together. The two most common are lists and dictionaries.

A list is an ordered collection of items, which can be of different types. A dictionary is an unordered collection of key-value pairs. You use a unique key to look up its associated value.

# A list of numbers
scores = [88, 92, 77, 95, 84]

# A dictionary storing user information
user_profile = {
  "username": "alex_p",
  "member_since": 2021,
  "is_active": True
}

Making Decisions and Repeating Tasks

A program isn't very useful if it just runs straight from top to bottom. We need it to make decisions and perform repetitive actions. This is handled by control structures. The most basic decision-making tool is the if statement. It checks if a condition is true and runs a block of code only if it is.

temperature = 75

if temperature > 80:
  print("It's a hot day!")
elif temperature < 60:
  print("It's a bit chilly.")
else:
  print("The weather is pleasant.")

boolean

adjective

A data type that has one of two possible values, typically denoted as true or false.

For repetitive tasks, we use loops. A for loop is perfect for iterating over a sequence, like a list. It will run a block of code once for each item in the sequence.

fruits = ["apple", "banana", "cherry"]

for fruit in fruits:
  print(f"I like to eat {fruit}s.")

Another type is the while loop, which continues to execute a block of code as long as a certain condition remains true. It's useful when you don't know in advance how many times you need to repeat the action.

count = 1

while count <= 5:
  print(f"Count is: {count}")
  count = count + 1 # Increment the count

Organizing Your Code

As your programs get more complex, you'll want to organize your code to keep it manageable and avoid repeating yourself. Functions are the main way to do this. A function is a reusable block of code that performs a specific task.

function

noun

A block of organized, reusable code that is used to perform a single, related action.

You define a function once and then can "call" it whenever you need it, potentially with different inputs.

# Define a function that adds two numbers
def add_numbers(x, y):
  return x + y

# Call the function with different inputs
sum1 = add_numbers(5, 10)
sum2 = add_numbers(100, -20)

print(sum1) # Output: 15
print(sum2) # Output: 80

Python also allows you to use code written by others through modules and libraries. A module is simply a file containing Python code. A library is a collection of related modules. You use the import statement to bring this external code into your program.

# Import the 'math' module to use its functions
import math

# Use the sqrt function from the math module
result = math.sqrt(64)

print(result) # Output: 8.0

Superpowers for Data

While Python's built-in features are powerful, its true strength in data science comes from specialized libraries. Two of the most important are NumPy and Pandas.

NumPy (Numerical Python) is the fundamental package for scientific computing. Its main feature is a powerful N-dimensional array object. These arrays are much faster and more memory-efficient for numerical operations than standard Python lists.

# Import the NumPy library
import numpy as np

# Create a NumPy array from a Python list
my_array = np.array([1, 2, 3, 4, 5])

# Perform a mathematical operation on the entire array
new_array = my_array * 2

print(new_array) # Output: [ 2  4  6  8 10]

Pandas is built on top of NumPy and is the go-to tool for data manipulation and analysis. It introduces two key data structures: the Series (a one-dimensional labeled array) and the DataFrame (a two-dimensional labeled structure with columns of potentially different types, like a spreadsheet or SQL table).

With Pandas, you can easily read data from files like CSVs, clean it, transform it, and perform complex analysis with just a few lines of code.

import pandas as pd

# Create a DataFrame from a dictionary
data = {'Name': ['Alice', 'Bob', 'Charlie'],
        'Age': [25, 30, 35],
        'City': ['New York', 'Los Angeles', 'Chicago']}

df = pd.DataFrame(data)

# Display the DataFrame
print(df)

This just scratches the surface, but mastering these basics is the first and most important step in using Python for data science. Now let's test your knowledge.

Quiz Questions 1/6

What is the primary purpose of a variable in Python?

Quiz Questions 2/6

If you need to iterate over a known sequence of items, like the elements in a list, which type of loop is most suitable?

With these fundamentals, you have the building blocks to start exploring, analyzing, and visualizing data.