Variables and Data Types in Python
Variables are names, not boxes
School often teaches that a variable is a box holding a value. In Python that picture is misleading.
A Python variable is a name that refers to an object. Assignment binds a name to an object; it doesn't copy a value into a container.
x = 10 # the name x now refers to the integer object 10
y = x # y refers to the SAME object
x = 20 # x now refers to a different object; y is unchanged
print(y) # 10
This matters later with lists, where two names referring to the same list means changing one changes "both".
Naming rules
Must:
- Begin with a letter or underscore
- Contain only letters, digits, underscores
- Not be a Python keyword (
if,for,class,None…)
Case-sensitive: total, Total and TOTAL are three different names.
Convention: snake_case for variables — student_name, total_marks.
The numeric types
| Type | Example | Notes |
|---|---|---|
int | 42, -7, 0 | Unlimited size in Python |
float | 3.14, -0.5, 2.0 | About 15–17 significant digits |
complex | 3+4j, 2j | j for the imaginary unit, not i |
bool | True, False | A subclass of int: True == 1 |
Integers have no upper limit. 2 ** 1000 computes exactly. This differs
from C or Java, and it's a genuine convenience.
Floats do not. They are binary approximations:
0.1 + 0.2 == 0.3 # False
0.1 + 0.2 # 0.30000000000000004
This isn't a Python bug — it's how binary floating point works everywhere. Never
compare floats with ==; compare within a tolerance:
abs((0.1 + 0.2) - 0.3) < 1e-9 # True
Strings
Text, in single or double quotes — no difference between them.
name = 'Anjali'
college = "Government Engineering College"
address = """Line one
Line two""" # triple quotes span lines
Strings are immutable. You cannot change one in place:
s = "hello"
s[0] = "H" # TypeError
s = "H" + s[1:] # make a new string instead
Useful operations:
len(s) # 5
s.upper() # 'HELLO' (returns new, s unchanged)
s[0] # 'h' first character
s[-1] # 'o' last character
s[1:4] # 'ell' slice, end excluded
"abc" + "def" # 'abcdef' concatenation
"ab" * 3 # 'ababab' repetition
Dynamic typing
The type belongs to the object, not the name. A name can refer to different types at different times:
x = 10 # int
x = "hello" # now a str — legal
Convenient, but it means type errors surface at runtime rather than being caught before the program runs.
Check a type with type(x).
Conversion
int("42") # 42
float("3.14") # 3.14
str(42) # '42'
int(3.9) # 3 truncates toward zero, does NOT round
int("3.9") # ValueError — cannot parse a decimal string as int
int(3.9) giving 3 is a common exam point: it truncates, it does not round.
Why input() needs conversion
input() always returns a string, whatever the user types.
age = input("Age: ") # user types 20 → age is the STRING "20"
age + 1 # TypeError
age = int(input("Age: ")) # correct
This is among the most frequent errors in first-semester lab work.