Write Python. Understand every error.

Starting Python in your browser…

Python basics · topic 3 of 25

Variables

A variable is a name that refers to a value. You create one with =, which means "store the value on the right under the name on the left". It does not mean "equals" as in maths.

city = "Kolkata"
students = 45
print(city, students)

A variable can be given a new value at any time. Python works out the right side first, so score = score + 5 takes the old score, adds 5, and stores the result. The shortcut score += 5 does the same thing.

Names may contain letters, digits and underscores, but cannot start with a digit or contain spaces. They are case-sensitive, so Total and total are different. Python programmers usually write names like total_marks.

Python can swap two variables in one line: a, b = b, a.

  • = stores a value; it does not compare.
  • The right side is calculated before storing.
  • x += 1 is short for x = x + 1.
  • Good names describe what the value means: price, not p.

Key takeaways

  • = stores a value. It does not compare two things.
  • The right side is worked out first, then stored under the name on the left.
  • x += 1 is short for x = x + 1.
  • Choose names that describe the value: price is clearer than p.

Common mistakes

Practise with these programs

Share this page:

Ctrl + Enter to run
Line 1, column 1Tab indents 4 spaces. Press Esc then Tab to leave the editor.