Variables & Data Types
Variables are the building blocks of every Python program — they store the data your code works with. Python's rich set of built-in data types handles everything from whole numbers and decimals to text, booleans, lists, and dictionaries. This chapter gives you a complete, hands-on mastery of all of them.
What are Variables?
A variable is a named container that stores a value in memory. You
create a variable simply by assigning a value to a name using the =
operator — no keyword, no type declaration needed.
In Python, variables are dynamically typed: the interpreter figures out the type from the value you assign. You can even reassign a variable to a completely different type later, which is valid Python.
# Creating variables — just assign a value
name = "Alice" # str
age = 25 # int
height = 5.6 # float
is_pro = True # bool
print(name, age, height, is_pro)
# Alice 25 5.6 True
# Dynamic typing — reassign to a different type
x = 10 # x is int
x = "hello" # x is now str — valid in Python
print(type(x)) # <class 'str'>
int x = 5;) or C++ (int x = 5;), Python requires no type keyword. Just write
x = 5 and Python handles the rest.
Variable Naming Rules
Python has strict rules for naming variables. Breaking them causes a SyntaxError. Follow the conventions below to write clean, professional code:
name, _private, myVar are all valid. 1name is not.user_age, score2 are fine. Spaces, hyphens, or symbols like @ are not allowed.age, Age, and AGE are three different
variables. Be consistent.for, if, while, class, True, None are reserved and cannot be variable names.# ✅ Valid names — snake_case (recommended for variables)
user_name = "Alice"
total_score = 99
_internal = True
item2 = "laptop"
# ❌ Invalid names — cause SyntaxError
# 2user = "Bob" ← starts with digit
# my-name = "Eve" ← hyphen not allowed
# for = 10 ← reserved keyword
# Constants — by convention use ALL_CAPS
MAX_SPEED = 300
PI = 3.14159
total_price) and PascalCase for class names (ShoppingCart). Constants use ALL_CAPS.
Python Built-in Data Types
Python has a rich set of built-in types grouped into categories. Every value in Python
is an object with a type, attributes, and methods. Use type(x) to inspect any variable's type at runtime.
Whole numbers of any size — positive, negative, or zero. No decimal point.
Example: age = 25
Numbers with a decimal point. Stored as 64-bit IEEE 754. Example: price = 19.99
Sequence of Unicode characters enclosed in quotes. Example: name = "Alice"
Only two values: True or False. Used in conditions and comparisons.
Ordered, changeable collection. Allows duplicates. Example: scores = [90, 85, 92]
Ordered, unchangeable collection. Faster than lists. Example: coords = (10, 20)
Collection of key-value pairs. Keys must be unique. Example: {"name":"Alice","age":25}
Unordered collection with no duplicates. Useful for membership
testing. Example: {1, 2, 3}
# Checking types with type()
x = 42
print(type(x)) # <class 'int'>
y = 3.14
print(type(y)) # <class 'float'>
s = "hello"
print(type(s)) # <class 'str'>
b = True
print(type(b)) # <class 'bool'>
lst = [1, 2, 3]
print(type(lst)) # <class 'list'>
tup = (10, 20)
print(type(tup)) # <class 'tuple'>
d = {"name": "Alice"}
print(type(d)) # <class 'dict'>
st = {1, 2, 3}
print(type(st)) # <class 'set'>
Numeric Types — int, float & complex
Python has three numeric types: int (whole numbers),
float (decimal numbers), and complex (numbers with a real and imaginary
part). You'll use int and float most
often.
# int — whole numbers (no size limit in Python 3)
population = 1_400_000_000 # underscores improve readability
negative = -50
binary = 0b1010 # binary → 10
hexa = 0xFF # hexadecimal → 255
# float — decimal numbers
pi = 3.14159
sci = 1.5e3 # scientific notation → 1500.0
tiny = 2.5e-4 # → 0.00025
# complex — real + imaginary
z = 3 + 4j
print(z.real, z.imag) # 3.0 4.0
# Arithmetic operators
print(10 + 3) # 13 — addition
print(10 - 3) # 7 — subtraction
print(10 * 3) # 30 — multiplication
print(10 / 3) # 3.333... — true division (always float)
print(10 // 3) # 3 — floor division
print(10 % 3) # 1 — modulus (remainder)
print(2 ** 8) # 256 — exponentiation
0.1 + 0.2
gives 0.30000000000000004. For financial calculations, use the decimal module instead.
Strings (str)
Strings are sequences of Unicode characters enclosed in single, double, or triple quotes. Python strings are immutable — you can't change a character in place, but you can create new strings with operations.
# Single, double, and triple quotes
a = 'hello'
b = "world"
c = """This is a
multi-line string"""
# String indexing and slicing
s = "Python"
print(s[0]) # P — first character
print(s[-1]) # n — last character
print(s[0:3]) # Pyt — slice from 0 up to (not including) 3
print(s[::-1]) # nohtyP — reverse
# Common string methods
print(s.upper()) # PYTHON
print(s.lower()) # python
print(s.replace("P","J")) # Jython
print(len(s)) # 6
# f-strings (Python 3.6+) — best practice
name = "Alice"
score = 98.5
print(f"Hello, {name}! Your score is {score:.1f}")
# Hello, Alice! Your score is 98.5
s[-1] is the last character.stop is
exclusive. s[::-1] reverses the string.:.2f for 2 decimal places, :, for
thousands separator."Py" in "Python" returns True. The in keyword tests substring
membership.Booleans & None
bool has only two values: True and
False. Booleans are a subclass of int — True equals 1 and False equals 0. Python also has a special
value None (like null in other
languages).
# Boolean values
is_active = True
is_admin = False
# Comparison operators return bool
print(10 > 5) # True
print(10 == 5) # False
print(10 != 5) # True
# bool() — convert to boolean
print(bool(0)) # False — zero is falsy
print(bool("")) # False — empty string is falsy
print(bool(42)) # True — any non-zero number is truthy
print(bool("hi")) # True — non-empty string is truthy
# None — represents absence of value
result = None
print(result is None) # True — use "is" not "==" to check None
False in a boolean context: 0, 0.0, "" (empty string), [] (empty list), {} (empty dict), () (empty tuple), None. Everything else is truthy.
Multiple Assignment
Python allows assigning multiple variables on a single line — great for swapping values without a temp variable:
# Assign multiple variables at once
x, y, z = 1, 2, 3
print(x, y, z) # 1 2 3
# Assign same value to multiple variables
a = b = c = 0
print(a, b, c) # 0 0 0
# Swap variables without a temp variable
p, q = 10, 20
p, q = q, p
print(p, q) # 20 10
Type Conversion (Casting)
Type conversion lets you convert a value from one type to another using built-in functions. Python has two kinds: implicit (done automatically) and explicit (you do it manually with casting functions).
# Implicit conversion — Python promotes int to float
result = 5 + 2.0
print(result, type(result)) # 7.0 <class 'float'>
# Explicit conversion — int(), float(), str(), bool()
print(int(3.9)) # 3 — truncates, does NOT round
print(int("42")) # 42 — string to int
print(float("3.14")) # 3.14 — string to float
print(str(100)) # "100" — int to string
print(bool(0)) # False — 0 is falsy
# Common use-case: reading user input
age_str = input("Enter your age: ") # returns str
age_int = int(age_str) # cast to int for math
print(f"You will be {age_int + 1} next year.")
| Function | Converts from | Example | Result |
|---|---|---|---|
int() |
float, str (numeric) | int("42") |
42 |
float() |
int, str (numeric) | float("3.14") |
3.14 |
str() |
int, float, bool | str(100) |
"100" |
bool() |
any type | bool(0) |
False |
list() |
tuple, set, str | list("abc") |
['a','b','c'] |
ValueError: int("hello") → ValueError: invalid literal for int(). Always validate user input before
casting.
Practice Python Online — Free Compilers
Don't want to install anything yet? Practice directly in your browser with these free Python environments.
- Variables are created by assignment (
x = 5) — no type declaration needed. Python infers the type from the value. - Use snake_case for variables and functions, PascalCase for classes, and ALL_CAPS for constants (PEP 8).
- Python's main data types: int, float, complex, str, bool, list, tuple, dict, set.
- Use
type(x)to check any variable's type at runtime. - Strings are immutable sequences. Use f-strings for formatting:
f"Hello, {name}!" - Falsy values:
0,"",[],{},(),None. Everything else is truthy. - Type casting: use
int(),float(),str(),bool(). Always validate input before casting. - Swap two variables elegantly:
a, b = b, a— no temporary variable needed.
Mutable objects can be changed after creation: list, dict, and set are mutable — you can add, remove, or modify elements.
Immutable objects cannot be changed: int, float, str, bool, and tuple are immutable.
When you "modify" an immutable value, Python creates a new object in memory. This distinction matters
for performance and when passing arguments to functions.
input() always returns a str
because the terminal can't know whether the user means a number or text — it only captures characters.
To use the input as a number, you must explicitly cast it: age = int(input("Age: ")). Always wrap in a try/except ValueError block if the input might not be a valid number,
to prevent your program from crashing on bad input.
== checks value equality — whether two objects
have the same value. is checks identity — whether
two variables point to the exact same object in memory. Example: a = [1, 2]; b = [1, 2] — a == b is
True (same values) but a is b
is False (different objects). Always use is when checking for None: if x is None:
int(3.9) returns 3, not 4. The int() function
truncates (cuts off) the decimal part — it does not round. This means int(3.1), int(3.5), and int(3.9) all return 3. If you need
rounding, use round(3.9) which returns 4, or math.floor() / math.ceil() for explicit floor/ceiling.
- 0 (int) — numeric zero represents "nothing" in mathematics, so Python treats it as False.
- 0.0 (float) — same reasoning as integer zero.
- "" (empty string) — an empty sequence has no content, so it's falsy.
- [] (empty list) — an empty collection contains no elements, treated as False.
- None — explicitly represents the absence of a value; always falsy.
type(3.0) return in Python?print(bool([]))?
Rate Us on Google
Join Our Learning Community
Connect with thousands of learners, get daily tips, ask questions and stay updated with new tutorials.