🌱 Phase 1 · Foundations 🟢 Beginner MODULE 02

Variables & Data Types

⏱️ 30 min read
📖 Theory + Code
🧩 5 Quiz Questions
🏗️ 1 Challenge
Your progress in Phase 133%
🎯 What you'll learn: How to create variables and store data in Python, the 5 core data types (int, float, str, bool, None), how to check types with type(), type conversion, multiple assignment, and naming best practices.

What is a Variable?

A variable is a named container that stores a value in your computer's memory. You give it a name, assign a value with =, and from that point on you can use that name anywhere in your program to refer to the value.

Think of a variable like a labelled box: you can put any value inside it, change the value later, and retrieve it whenever you need it.

💡
Variables are case-sensitive
name, Name, and NAME are three completely different variables in Python. Always be consistent with capitalisation.
variables_intro.py
PYTHON
# Creating variables — just use = (no keyword needed!)
name = "Aisha"        # stores a text value
age = 17             # stores a whole number
gpa = 3.85           # stores a decimal number
is_enrolled = True  # stores True or False

# Using variables
print(name)          # Output: Aisha
print(age)           # Output: 17
print(gpa)           # Output: 3.85
print(is_enrolled)   # Output: True

# You can reassign a variable anytime
age = 18
print(age)           # Output: 18  (the old value is gone)
No need to declare types!
Unlike Java or C++, Python figures out what type a variable is automatically. This is called dynamic typing — it makes Python much faster to write.

Naming Rules & Best Practices

Variable names must follow specific rules, and following good conventions makes your code professional and readable.

Must start with a letter or _
Valid: name, _count, my_var. Never start with a digit.
Letters, digits, underscores only
No spaces, hyphens, or special characters. my_name ✅   my-name
⚠️
No reserved keywords
You can't name a variable for, if, class, True, etc. — Python uses those words itself.
🐍
Use snake_case style
Python convention: all lowercase with underscores. first_name ✅   firstName (JS style) — technically works but not Pythonic.
naming_rules.py
PYTHON
# ✅ VALID variable names
student_name = "Ali"
total_marks = 450
_private = "hidden"
score2 = 99

# ❌ INVALID — Python will throw a SyntaxError
# 2score = 99      (starts with number)
# my-score = 99    (hyphen not allowed)
# my score = 99    (space not allowed)
# class = "A"      (reserved keyword)

# 🐍 Python style — snake_case is the standard
first_name = "Sara"      # ✅ Pythonic
firstName = "Sara"       # works but not recommended
FIRST_NAME = "Sara"      # UPPERCASE = constant (by convention)
⚠️
Reserved keywords you cannot use as variable names
False True None and or not if elif else for while break continue return def class import from try except pass lambda in is del

Python's Core Data Types

Every value in Python has a type. The five most important types you'll use every day are:

🔢
int
Integer
Whole numbers — positive, negative, or zero. No decimal point.
age = 17  |  score = -5  |  population = 1000000
💧
float
Floating Point
Decimal numbers. Any number with a . (dot) is a float.
gpa = 3.85  |  pi = 3.14159  |  temp = -2.5
📝
str
String
Text — any sequence of characters inside quotes (single or double).
name = "Ali"  |  city = 'Lahore'  |  msg = "Hello!"
🔘
bool
Boolean
Only two values: True or False. Essential for conditions.
is_active = True  |  is_admin = False
None
NoneType — The absence of a value
Represents "nothing" or "no value yet". Used to initialise variables before assigning real data, or as a return value from functions that don't return anything explicitly.
result = None  |  user = None  |  error_msg = None
data_types.py
PYTHON
# int — whole numbers
students = 30
temperature = -5
big_number = 1_000_000   # underscores allowed for readability

# float — decimal numbers
price = 19.99
pi = 3.14159
scientific = 2.5e6       # scientific notation = 2,500,000.0

# str — text (single or double quotes, both work)
city = "Lahore"
country = 'Pakistan'
greeting = "Hello, World!"

# bool — True / False (capital T and F!)
logged_in = True
is_weekend = False

# None — absence of value
result = None
print(result)             # Output: None

Checking Types with type()

Python's built-in type() function tells you exactly what type a variable or value is. This is incredibly useful for debugging — especially when a program isn't behaving as expected.

type_function.py
PYTHON
print(type(42))          # <class 'int'>
print(type(3.14))        # <class 'float'>
print(type("hello"))    # <class 'str'>
print(type(True))        # <class 'bool'>
print(type(None))        # <class 'NoneType'>

# With variables
score = 95
print(type(score))       # <class 'int'>

# Notice: "42" is a string, not an integer!
print(type("42"))        # <class 'str'>
print(type(42))          # <class 'int'>
# These are NOT the same — quotes make it text!

# Tricky ones to watch out for
print(type(True))        # <class 'bool'>
print(type(1))           # <class 'int'>  — 1 is NOT True!
🎭
Fun fact: bool is a subclass of int
In Python, True equals 1 and False equals 0 when used in arithmetic. Try: print(True + True) — it outputs 2! This is intentional and occasionally useful, but mostly a quirk to be aware of.

Type Conversion (Casting)

Sometimes you need to convert a value from one type to another. For example, user input is always a string — if you want to do maths with it, you must convert it to int or float first.

FunctionConverts toExampleResult
int(x)Integerint("42")42
float(x)Floatfloat("3.14")3.14
str(x)Stringstr(100)"100"
bool(x)Booleanbool(0)False
int(float)Integer (truncates)int(9.99)9
type_conversion.py
PYTHON
# User input always comes in as a string
user_age = input("Enter your age: ")
print(type(user_age))          # <class 'str'>

# Convert string to int before calculating
age = int(user_age)
birth_year = 2025 - age
print("Birth year:", birth_year)

# Convert int to string (needed to join with text)
score = 95
message = "Your score: " + str(score)
print(message)                 # Your score: 95

# bool() — falsy values in Python:
print(bool(0))        # False  (zero is falsy)
print(bool(""))       # False  (empty string is falsy)
print(bool(None))     # False  (None is falsy)
print(bool(42))       # True   (any non-zero number is truthy)
print(bool("hello")) # True   (any non-empty string is truthy)
⚠️
Conversion can fail — always validate user input
int("hello") will crash with a ValueError. In real programs, you wrap conversions in try / except blocks to handle invalid input gracefully — you'll learn this in Phase 3.

Multiple Assignment & Constants

Python lets you assign variables in several convenient ways, and has a convention for values that should never change.

multiple_assignment.py
PYTHON
# Assign the same value to multiple variables
x = y = z = 0
print(x, y, z)           # 0 0 0

# Assign multiple values in one line (tuple unpacking)
name, age, city = "Zara", 20, "Karachi"
print(name)               # Zara
print(age)                # 20
print(city)               # Karachi

# Swap two variables — Python magic!
a, b = 10, 20
a, b = b, a             # swap in one line
print(a, b)               # 20 10

# ─────────────────────────────────────
# CONSTANTS — use ALL_CAPS by convention
# Python has no true constants, but naming
# them in CAPS signals "don't change this"
MAX_STUDENTS = 40
PI = 3.14159
APP_NAME = "BitWithBite"
VERSION = "2.0.1"
Augmented assignment operators
Python has shorthand operators to update a variable: x += 5 (add 5), x -= 3 (subtract 3), x *= 2 (multiply by 2), x //= 4 (floor-divide by 4). These are the same as x = x + 5 etc. but shorter and cleaner.
augmented_operators.py
PYTHON
score = 100
score += 50     # score = score + 50  →  150
score -= 20     # score = score - 20  →  130
score *= 2      # score = score * 2   →  260
score //= 5     # score = score // 5  →  52
print(score)    # 52
🧩 Knowledge Check
5 questions — test your understanding of Variables & Data Types
1. Which of the following is a valid Python variable name?
2. What does type(3.14) return?
3. What does bool("") return?
4. Which converts the string "99" into the integer 99?
5. What does x = y = z = 0 do?
🏗️
Coding Challenge — Student Profile
Apply everything from this lesson in one mini program
Task: Create a student profile program that:

1. Stores a student's name (str), age (int), GPA (float), and is_scholarship_holder (bool)
2. Prints each variable with a label using the print() function
3. Prints the type() of each variable
4. Converts age to a string and joins it with the message "Student age: "
5. Increases the student's GPA by 0.1 using an augmented assignment operator
💡 Show hints
  • Use str(age) to convert an integer to a string before joining with +
  • Use gpa += 0.1 to increase GPA
  • Use print("Name:", name) to print with a label
  • Capital T and F for True / False
student_profile.py — Sample Solution
PYTHON
# ── Student Profile ──────────────────────────
name                 = "Fatima Malik"
age                  = 19
gpa                  = 3.72
is_scholarship_holder = True

# Print with labels
print("Name:", name)
print("Age:", age)
print("GPA:", gpa)
print("Scholarship:", is_scholarship_holder)

# Print types
print(type(name), type(age), type(gpa), type(is_scholarship_holder))

# Convert age to string
print("Student age: " + str(age))

# Augmented assignment
gpa += 0.1
print("Updated GPA:", gpa)
🎉
Lesson 2 Complete!
You've mastered Python variables and data types. Ready for the next lesson?
← Course Home
Phase 1 · FoundationsLesson 2 of 6