Variables

Nerd Cafe

What is a Variable?

A variable is a name that refers to a value stored in memory. Think of it as a box with a label that stores data. In machine learning, variables help us manage data, features, models, and results.

1. Declaring Variables

x = 5
name = "Mr Nerd"
price = 19.99
is_active = True

Practical Notes:

  • x is an integer

  • name is a string

  • price is a float

  • is_active is a boolean

No need to declare the type in Python — it figures it out!

2. Variable Naming Rules (Very Important in ML Projects)

# Valid
data = [1, 2, 3]
learning_rate = 0.01
model_name = "LinearRegression"

# Invalid
# 1model = "wrong"   ❌ Starts with a number
# learning-rate = 0.01  ❌ Hyphen not allowed

Best Practices (PEP8 Style Guide for ML Code):

  • Use lowercase with underscores: train_data, test_accuracy

  • Be descriptive: input_vector instead of iv

  • Avoid keywords: class, def, etc.

3. Updating Variables

accuracy = 0.85
accuracy = accuracy + 0.05  # Now it's 0.90

Shortcuts:

accuracy += 0.05  # same as above

4. Data Types in Machine Learning

# Common data types
integer_example = 10           # int
float_example = 3.14           # float
string_example = "NeuralNet"   # str
boolean_example = False        # bool
list_example = [1, 2, 3]       # list
tuple_example = (1, 2)         # tuple
dict_example = {"lr": 0.01}    # dict

5. Practical Use in ML:

features = [5.1, 3.5, 1.4, 0.2]   # input features (list of floats)
label = "Iris-setosa"            # target label (string)
params = {"learning_rate": 0.01, "epochs": 100}  # dictionary for config

6. Multiple Assignments

x, y, z = 1, 2, 3

# Use this for splitting ML data
train_data, test_data = [1, 2], [3, 4]

7. Constants (Not Built-in, But You Can Use UPPERCASE)

LEARNING_RATE = 0.01
EPOCHS = 100

Tip: Use ALL_CAPS to indicate values that should not change.

8. Type Checking (Important in Debugging ML Code)

data = [1, 2, 3]
print(type(data))  # <class 'list'>

9. Variable Scope (Global vs Local)

score = 90  # global

def update_score():
    score = 100  # local to this function
    print("Inside function:", score)

update_score()
print("Outside function:", score)

Output:

Inside function: 100
Outside function: 90

Variables inside functions do not change the global ones unless specified.

10. Dynamic Typing

Python is dynamically typed — you can reassign variables to different types.

x = 10      # x is int
x = "hi"    # now x is str

Be careful in ML code! Accidentally changing data types can cause bugs.

11. Example in a Mini Machine Learning Context

# Step 1: Define hyperparameters
LEARNING_RATE = 0.01
EPOCHS = 100

# Step 2: Data
features = [5.1, 3.5, 1.4, 0.2]
label = "Iris-setosa"

# Step 3: Simulate a training log
accuracy = 0.75
accuracy += 0.05  # New accuracy
print(f"Final accuracy: {accuracy}")

12. Using Variables in NumPy (Essential for ML)

import numpy as np

x = np.array([1, 2, 3])
w = np.array([0.4, 0.3, 0.2])
bias = 0.5

# Linear combination
y = np.dot(x, w) + bias
print("Output:", y)

Output:

Output: 2.1

Summary Table

Feature
Example
Notes

Basic variable

x = 5

Auto-detects type

Multiple assign

x, y = 1, 2

Split values

Type check

type(x)

Debugging help

Update value

x += 1

Shortcut for updating

Store parameters

params = {"lr": 0.01}

Common in ML projects

Constants

EPOCHS = 100

Use ALL_CAPS

Keywords

variables in python, python variable types, declaring variables, variable naming rules, python data types, python for machine learning, python constants, variable scope, python assignment, python beginner guide, python tutorial, python variable examples, variable best practices, python dynamic typing, python debugging, python multiple assignment, machine learning python code, python type checking, python variables cheat sheet, python variable use in ML, nerd cafe

Last updated