Follow AiTechWorlds on LinkedIn for professional AI content!Follow Now →
18 minLesson 2 of 34
Python Foundations

Variables, Data Types & Operators

Variables, Data Types & Operators

Understanding how Python stores, classifies, and manipulates data is the single most important foundation you can build. Get this right and every other concept clicks faster. Rush past it and you'll hit confusing bugs for months.

Variable Assignment

In Python, a variable is a name that points to a value. Assignment is done with =:

name = "Alice"
age = 30
height = 1.75
is_student = True
nothing = None

print(name)    # Alice
print(age)     # 30
print(height)  # 1.75

Python lets you assign multiple variables on one line:

x, y, z = 10, 20, 30
print(x, y, z)  # 10 20 30

# Swap two values — no temp variable needed
a, b = 5, 9
a, b = b, a
print(a, b)  # 9 5

Variable names must start with a letter or underscore, contain only letters, digits, and underscores, and are case-sensitive. score, Score, and SCORE are three different variables.

Python's Dynamic Typing

Python is dynamically typed — you don't declare a type. Python figures it out at runtime:

x = 42          # x is an int
x = "hello"     # now x is a str — totally valid
x = [1, 2, 3]   # now x is a list

This flexibility is powerful but also a source of bugs. A variable that used to hold a number suddenly holds a string will cause errors if you treat it like a number later.

The 5 Core Types

1. int — Whole Numbers

score = 100
negative = -42
big_number = 1_000_000  # underscores for readability

print(type(score))      # <class 'int'>
print(type(big_number)) # <class 'int'>

Integers in Python have unlimited precision — no overflow errors:

print(2 ** 100)  # 1267650600228229401496703205376

2. float — Decimal Numbers

price = 19.99
temperature = -3.5
scientific = 1.5e10  # 15000000000.0

print(type(price))  # <class 'float'>

Be aware of floating-point precision quirks:

print(0.1 + 0.2)       # 0.30000000000000004
print(0.1 + 0.2 == 0.3) # False — this is a classic beginner trap!

# Use round() when comparing floats
print(round(0.1 + 0.2, 10) == 0.3)  # True

3. str — Text

greeting = "Hello"
language = 'Python'
multiline = """This spans
multiple lines."""

print(type(greeting))  # <class 'str'>
print(len(greeting))   # 5

4. bool — True or False

is_logged_in = True
has_errors = False

print(type(is_logged_in))  # <class 'bool'>

# Booleans are actually integers under the hood
print(True + True)   # 2
print(True * 10)     # 10
print(False + 5)     # 5

5. None — The Absence of a Value

result = None  # "nothing here yet"

print(result)        # None
print(type(result))  # <class 'NoneType'>

# Always check for None with 'is', not '=='
if result is None:
    print("No result yet")

Checking Types: type() and isinstance()

x = 42

print(type(x))           # <class 'int'>
print(type(x) == int)    # True

# isinstance() is preferred — it handles inheritance
print(isinstance(x, int))         # True
print(isinstance(x, (int, float))) # True — checks multiple types at once

name = "Alice"
print(isinstance(name, str))  # True
print(isinstance(name, int))  # False

Use isinstance() in production code. It's more flexible and more Pythonic.

Arithmetic Operators

a, b = 17, 5

print(a + b)   # 22  — addition
print(a - b)   # 12  — subtraction
print(a * b)   # 85  — multiplication
print(a / b)   # 3.4 — true division (always returns float)
print(a // b)  # 3   — floor division (rounds down)
print(a % b)   # 2   — modulo (remainder)
print(a ** b)  # 1419857 — exponentiation

The // and % operators are essential for real problems:

# Convert 135 minutes to hours and minutes
total_minutes = 135
hours = total_minutes // 60    # 2
minutes = total_minutes % 60   # 15
print(f"{hours}h {minutes}m")  # 2h 15m

# Check if a number is even or odd
number = 7
if number % 2 == 0:
    print("even")
else:
    print("odd")  # odd

Comparison Operators

Comparison operators return True or False:

x, y = 10, 20

print(x == y)   # False — equal to
print(x != y)   # True  — not equal to
print(x < y)    # True  — less than
print(x > y)    # False — greater than
print(x <= 10)  # True  — less than or equal to
print(x >= 10)  # True  — greater than or equal to

Python allows chaining comparisons — this is unique and very readable:

age = 25
print(18 <= age < 65)  # True — both conditions must hold
print(1 < 2 < 3 < 4)   # True

Logical Operators

x = 5

print(x > 0 and x < 10)   # True  — both must be True
print(x < 0 or x > 3)     # True  — at least one must be True
print(not x > 0)           # False — inverts the boolean

# Short-circuit evaluation — Python stops early
data = None
result = data or "default"
print(result)  # default

name = "Alice"
output = name and name.upper()
print(output)  # ALICE

Augmented Assignment

These are shortcuts that modify a variable in place:

score = 100

score += 10   # score = score + 10 → 110
score -= 5    # score = score - 5  → 105
score *= 2    # score = score * 2  → 210
score //= 3   # score = score // 3 → 70
score **= 2   # score = score ** 2 → 4900

print(score)  # 4900

Type Conversion

Convert between types explicitly using built-in functions:

# String to number
age_str = "25"
age_int = int(age_str)
print(age_int + 5)   # 30

price_str = "19.99"
price = float(price_str)
print(price * 2)     # 39.98

# Number to string
count = 42
message = "You have " + str(count) + " messages"
print(message)  # You have 42 messages

# To boolean — almost everything is truthy
print(bool(1))      # True
print(bool(0))      # False
print(bool("hi"))   # True
print(bool(""))     # False
print(bool([1, 2])) # True
print(bool([]))     # False
print(bool(None))   # False

f-Strings: Clean String Formatting

f-strings (formatted string literals) are the modern way to embed values in strings:

name = "Alice"
age = 30
height = 1.752

# Basic embedding
print(f"Name: {name}, Age: {age}")  # Name: Alice, Age: 30

# Expressions inside braces
print(f"In 10 years: {age + 10}")   # In 10 years: 40

# Format numbers
print(f"Height: {height:.2f}m")     # Height: 1.75m
print(f"Price: ${19.9:.2f}")        # Price: $19.90

# Width and alignment
print(f"{'Left':<10}|{'Right':>10}")  # Left      |     Right

Common Beginner Mistakes

Mistake 1: Using = instead of == in comparisons

x = 5
# Wrong — this assigns 10 to x inside if (syntax error in Python, logic error elsewhere)
# if x = 10:

# Correct
if x == 10:
    print("ten")

Mistake 2: Concatenating str and int directly

age = 25
# Wrong — TypeError: can only concatenate str (not "int") to str
# print("Age: " + age)

# Correct
print("Age: " + str(age))  # Age: 25
print(f"Age: {age}")        # Age: 25 — f-strings handle this automatically

Mistake 3: Floating-point equality

# Wrong — unreliable due to floating-point representation
total = 0.1 + 0.2
if total == 0.3:
    print("equal")  # this won't print!

# Correct — use round() or math.isclose()
import math
if math.isclose(total, 0.3):
    print("equal")  # equal

Mistake 4: Forgetting that None is not zero or empty string

value = None

# Wrong — comparing None to 0 is always False
if value == 0:
    print("zero")

# Correct
if value is None:
    print("nothing")  # nothing

Quick Reference

TypeExampleTruthy?
int42Yes (unless 0)
float3.14Yes (unless 0.0)
str"hello"Yes (unless "")
boolTrueYes
NoneNoneNo

What's Next

You now understand how Python stores and manipulates data at its most fundamental level. In the next lesson, we go deep on strings — Python's most versatile type — covering indexing, slicing, and the full arsenal of string methods.

📱

Get this course's notes on Telegram!

Free cheat sheets, summaries & practice exercises

Get Notes Free →
!