Variables & Data Types
Variables and data types are the building blocks of every Python program. Understanding how Python stores data, what types it supports, and how types behave is essential for writing correct and predictable code.
Why This Chapter Matters
Every real program stores and manipulates data. Without a solid understanding of variables and types, you will spend too much time chasing bugs caused by unexpected behavior.
- you will understand why
"5" + 5raises an error - you will know when to use
intvsfloatvsstr - you will understand Python's dynamic typing model
- you will know how to inspect and convert types
What Variables Are
A variable is a named reference to a value stored in memory. In Python, you do not declare a type — Python figures it out automatically.
name = "Asha"
age = 16
score = 98.5
is_active = True
Variables can be reassigned to new values, even of a different type:
x = 10
x = "now I am a string" # perfectly valid in Python
Naming Rules and Conventions
- Must start with a letter or underscore (
_), not a digit - Can contain letters, digits, and underscores
- Case-sensitive:
nameandNameare different variables - Cannot be Python reserved keywords (
if,for,class, etc.) - Convention: use snake_case for variables (
my_variable_name)
first_name = "Leo"
total_score = 42
_private_value = True
# 2fast = False # Error — cannot start with a digit
Python's Built-In Data Types
Strings (str)
Strings store text. Use single quotes, double quotes, or triple quotes.
greeting = "Hello, World!"
city = 'Mumbai'
paragraph = """This is a
multi-line string."""
String operations:
name = "python"
print(name.upper()) # PYTHON
print(name.capitalize()) # Python
print(name[0]) # p (indexing)
print(name[1:4]) # yth (slicing)
print(len(name)) # 6
print("py" in name) # True
f-strings (formatted string literals) — the modern way to embed values in strings:
name = "Asha"
age = 16
print(f"My name is {name} and I am {age} years old.")
Integers (int)
Whole numbers, positive or negative, with no decimal point.
count = 100
negative = -42
big = 1_000_000 # underscores for readability
print(type(count)) # <class 'int'>
Integer operations:
print(10 // 3) # 3 (floor division)
print(10 % 3) # 1 (modulo — remainder)
print(2 ** 10) # 1024 (exponentiation)
Floats (float)
Numbers with a decimal point.
price = 19.99
pi = 3.14159
scientific = 1.5e10 # 15000000000.0
Be careful with floating-point precision:
print(0.1 + 0.2) # 0.30000000000000004 — floating-point quirk
Booleans (bool)
Only two values: True or False.
is_logged_in = True
has_permission = False
print(type(is_logged_in)) # <class 'bool'>
Booleans are actually subclasses of int in Python:
print(True + True) # 2
print(True == 1) # True
NoneType (None)
None represents the intentional absence of a value. It is Python's equivalent of null.
result = None
print(result is None) # True (use 'is' to check for None)
Type Checking
Use type() to see what type a value is:
print(type("hello")) # <class 'str'>
print(type(42)) # <class 'int'>
print(type(3.14)) # <class 'float'>
print(type(True)) # <class 'bool'>
print(type(None)) # <class 'NoneType'>
Use isinstance() to check if a value matches a type:
x = 42
print(isinstance(x, int)) # True
print(isinstance(x, float)) # False
print(isinstance(x, (int, float))) # True — check against multiple types
Type Conversion (Casting)
Convert between types explicitly:
# String to number
age_str = "25"
age_int = int(age_str) # 25
age_float = float(age_str) # 25.0
# Number to string
score = 98
score_str = str(score) # "98"
# Float to int (truncates, does NOT round)
pi = 3.99
print(int(pi)) # 3
Conversion can fail — always be prepared:
try:
num = int("hello") # ValueError!
except ValueError:
print("Cannot convert that to an integer")
Multiple Assignment
Python supports assigning multiple variables in one line:
x, y, z = 1, 2, 3
a = b = c = 0 # all three point to the same value
first, *rest = [1, 2, 3, 4, 5] # starred assignment
print(first) # 1
print(rest) # [2, 3, 4, 5]
Constants Convention
Python has no built-in const keyword. By convention, use ALL_CAPS for values that should not change:
MAX_SCORE = 100
PI = 3.14159
APP_NAME = "Nandhoo"
This is a convention only — nothing prevents reassignment, but it signals intent to other developers.
Truthiness and Falsiness
Every Python value has a boolean equivalent when used in a condition.
Falsy values (evaluate as False):
False0,0.0""(empty string)[](empty list),{}(empty dict),()(empty tuple)None
Everything else is truthy:
if "hello":
print("Non-empty string is truthy")
if []:
print("This never runs — empty list is falsy")
if 0:
print("Zero is falsy")
Practical Uses
- storing user input from
input() - tracking scores, counts, and flags
- building dynamic strings with f-strings
- representing yes/no decisions with booleans
- working with optional values using
None
Common Mistakes
- comparing with
== Noneinstead ofis None - forgetting that
int("3.5")fails — you needint(float("3.5")) - expecting
0.1 + 0.2 == 0.3to beTrue(it is not) - using a mutable default value (like a list) as a default parameter
Mini Exercises
- Create variables for your name, age, height, and whether you are a student.
- Use an f-string to print them all in one sentence.
- Convert the string
"42"to an integer and perform math with it. - Write a check using
isinstance()to verify if a value is either an int or float. - Test which values are falsy by putting them inside an
ifstatement.
Review Questions
- What is the difference between
int,float, andstr? - How does Python's type system differ from languages like Java or C++?
- What is the difference between
type()andisinstance()? - Why is
Nonechecked withisinstead of==? - What are three examples of falsy values in Python?
Reference Checklist
- I can declare variables and assign values without declaring a type
- I understand all five primitive types: str, int, float, bool, None
- I can use
type()andisinstance()to inspect values - I can convert between types with
int(),float(),str() - I can use f-strings to build dynamic strings
- I understand truthy and falsy values