Variables in Python

How names attach to values, why Python needs no type declaration, and the one thing that surprises everybody about assignment.

4 minute read · Free · Taught properly in our Python Training in Amritsar

A variable in Python is a name pointing at a value. That is the whole idea, and it is worth saying plainly because it is different from C or Java, where a variable is a box of a fixed size and type.

name = "Simran"
age = 19
fee = 4500.0
is_enrolled = True

No int, no String, no declaration. Python works out the type from what you put in, and you can put something else in later:

x = 5        # x is an int
x = "five"   # now x is a str, and that is legal

The four types you will use constantly

  • int — whole numbers: 19, -3, 1000000
  • float — numbers with a decimal point: 4500.0, 3.14
  • str — text, in single or double quotes: "Amritsar"
  • boolTrue or False, capital first letter

You can always ask:

print(type(fee))    # <class 'float'>

Naming

Lowercase, words joined with underscores: student_name, total_fee. Not StudentName, which Python programmers reserve for class names. Names cannot start with a digit and cannot be words Python already uses — class, for, if, return.

Use names that say what the thing is. a, b, temp will cost you an hour next week when you reread your own code.

The bit that trips people up

Assignment copies the reference, not the value. With numbers and strings you never notice:

a = 5
b = a
b = 6
print(a)    # 5 — unchanged

With a list you do:

first = [1, 2, 3]
second = first
second.append(4)
print(first)    # [1, 2, 3, 4] — first changed too

Both names point at the same list. There is only one list. If you want a real copy, ask for one: second = first.copy().

This catches at least one person in every batch, usually while debugging something unrelated for half an hour first. Now you know what you are looking at.

Input is always text

age = input("Your age: ")
print(age + 1)     # TypeError

input() hands back a string even when the person typed digits. Convert it:

age = int(input("Your age: "))

Stuck on this in your own code?

That is what a class is for. Sit one for free at WebPrims on Majitha Road, Amritsar — write some Python, ask the mentor why yours is not working, and decide afterwards.