🐍 Python Tutorial

Python Variables

Learn how to use variables in Python effectively.

Python Variables

Variables store data values in Python. Unlike some languages, you don't need to declare a type — Python figures it out for you.

x = 10
name = "Rahul"
is_active = True
print(x, name, is_active)

Naming Rules

  • Must start with a letter or underscore
  • Can contain letters, numbers, and underscores
  • Case-sensitive (age and Age are different variables)

Reassigning Variables

count = 1
count = count + 1
print(count)  # 2

Common Errors & Troubleshooting

  • NameError: name 'x' is not defined — you tried to use a variable before assigning it a value, or misspelled its name. Python has no concept of "declaring" a variable in advance; the first assignment is what creates it.
  • SyntaxError: invalid syntax when starting a variable name with a number — variable names can't start with a digit (1count = 5 fails). Start with a letter or underscore instead (count1 = 5 is fine).
  • A value "disappears" after reassignment — remember count = count + 1 doesn't create a second variable; it overwrites count's old value entirely. If you need the previous value too, save it to a different variable first.