Learn Python Variables and Data Types

Variables and Data Types

⏱ 15 min read
A variable is a name that points to a value. Python is dynamically typed — you don't declare the type, Python figures it out automatically.

The 4 Core Types:

int — stores whole numbers (unlimited size in Python!)
Example: age = 25

float — stores decimal numbers
Example: price = 9.99

bool — stores only True or False (capital T and F!)
Example: is_student = True

str — stores text (single or double quotes — same thing)
Example: name = "Alice"

Other Types:
None — represents no value (like null in Java)
complex — complex numbers: 3+4j

String Operations:
name = "Alice"
name.upper() — "ALICE"
name.lower() — "alice"
len(name) — 5
name[0] — "A" (first character)
name[-1] — "e" (last character)
name[1:4] — "lic" (slicing)
name.contains("li") → name — "li" in name → True

f-Strings — The Best Way to Format:
f"Hello, {name}!" — embed variable
f"Price: ${price:.2f}" — 2 decimal places
f"Next year: {age + 1}" — expressions work too!

Constants:
Python has no final keyword. Use ALL_CAPS names by convention to signal a constant.
Example: PI = 3.14159 / MAX_STUDENTS = 30

Naming Rules:
Use snake_case: first_name, total_score, is_active
Constants are ALL_CAPS: MAX_SIZE, PI
Python is case-sensitive: name, Name, and NAME are different.
Code Example
# Python detects types automatically — no declaration needed
age        = 25
price      = 9.99
is_student = True
name       = "Alice"
 
print(type(age))        # <class 'int'>
print(type(price))      # <class 'float'>
print(type(is_student)) # <class 'bool'>
print(type(name))       # <class 'str'>
 
# String operations
greeting = f"Hello, {name}!"
print(greeting)                  # Hello, Alice!
print(f"Name length: {len(name)}")  # Name length: 5
print(f"Uppercase: {name.upper()}")  # Uppercase: ALICE
print(f"Has 'li': {'li' in name}")   # Has 'li': True
 
# Type conversion
num_str = "42"
num     = int(num_str)   # string → int
pi_str  = "3.14"
pi      = float(pi_str)  # string → float
score   = 95
message = "Your score: " + str(score)  # int → string
print(message)
 
# Constants (ALL_CAPS convention)
PI           = 3.14159
MAX_STUDENTS = 30
print(f"Pi = {PI}")
print(f"Max students = {MAX_STUDENTS}")
 
# Output:
# Hello, Alice!
# Name length: 5
# Uppercase: ALICE
# Has 'li': True
# Your score: 95
# Pi = 3.14159
# Max students = 30
← Python: Getting Started Operators and Math →

Log in to track your progress and earn badges as you complete lessons.

Log In to Track Progress