A Python variable is a name pointing at a value. You create one by assigning to it — there is no declaration step and no type to write.
city = "Karachi"
population = 15000000
average_rating = 4.6
is_coastal = TrueAssignment happens right to left#
total = 10 + 5 # the right side is worked out first, then stored
print(total) # 15This is why count = count + 1 makes sense in code even though it is nonsense in algebra. Python has a shorthand for it:
count = 0
count += 1 # same as count = count + 1
count -= 1
count *= 3Naming rules and conventions#
Rules that Python enforces:
- Start with a letter or underscore, never a digit
- Only letters, digits and underscores — no spaces or dashes
- Case sensitive:
Totalandtotalare different - Cannot be a keyword such as
class,for,lambdaorNone
Conventions the community follows:
snake_casefor variables and functions:user_emailCAPITALSfor values treated as constants:TAX_RATE = 0.17- A leading underscore for internal details:
_cache
Assigning several at once#
x, y = 3, 4
a = b = c = 0
# swapping without a temporary variable
x, y = y, xThat swap line is a small piece of Python that people genuinely enjoy.
Deleting and checking#
score = 10
print(type(score)) # <class 'int'>
del score
print(score) # NameErrorYou rarely need del. type() on the other hand is one of the most useful debugging tools you have — see Python data types explained.
The behaviour that surprises people#
For numbers and text, assigning makes an independent copy in every way that matters:
a = 5
b = a
b = 10
print(a) # 5 — unaffectedFor lists and dictionaries, both names point at the same object:
a = [1, 2, 3]
b = a
b.append(4)
print(a) # [1, 2, 3, 4] — a changed tooTo get a real copy:
b = a.copy() # or list(a), or a[:]Global and local#
A variable created inside a function belongs to that function.
counter = 0
def increment():
counter = 5 # a new local variable, not the outer one
increment()
print(counter) # still 0Rather than reaching for the global keyword, return the value instead. Functions that only depend on their inputs are far easier to test and reason about. See Python functions explained.
Questions people ask#
Does Python have constants?
Not enforced ones. Writing a name in capitals is a convention that tells other programmers not to change it, but Python will not stop you.
What is None?
Python’s way of saying “no value”. Functions without a return hand back None. Check for it with if value is None: rather than == None.
Can I annotate types?
Yes: age: int = 30. Python does not enforce it, but editors use annotations to catch mistakes and improve autocomplete. Useful in bigger projects, optional when learning.