Python Variables: Names, Assignment and Types
A variable gives a name to a value so you can use it later. In Python you create one simply by assigning to it; there is no declaration keyword and no type to state in advance.
Assignment binds a name to a value
city = "Denver" evaluates the right-hand side, then makes the name city refer to the resulting value. The single = means "bind", not "equals"; comparing values uses ==, covered in the booleans chapter.
Assigning again does not change the old value. It simply points the name at a new one. That is why population = population + 1000 works: Python computes the new number using the old binding, then rebinds the name.
Values have types, names do not
Every value has a type, such as str for text or int for whole numbers. The name itself has no fixed type, so the same variable could hold a number now and text later. That flexibility is convenient, but in practice keep one meaning per name to stay readable. The built-in type() function tells you what kind of value a name currently refers to.
Expected output
Denver 715522 716522 20 10 <class 'str'> <class 'int'>
Two more features appear above. x, y = 10, 20 assigns several names at once by position. x, y = y, x swaps two values in one line, because Python builds the right-hand side completely before assigning anything. The underscore in 715_522 is only a visual separator for long numbers.
Naming rules and conventions
Names may contain letters, digits and underscores, and must not start with a digit. They are case-sensitive: total and Total are different. Reserved words such as if, for and class cannot be used. By convention, Python variables use snake_case: lowercase words joined by underscores, like max_speed. Choose names that say what the value means; price_usd beats p.
Common mistakes
- Using a name before assigning it, which raises
NameError. - Reading
=as a comparison.x = 5stores;x == 5asks a question. - Shadowing built-ins, for example naming a variable
listorprint, which hides the built-in function for the rest of the program.
Summary
name = valuecreates or rebinds a variable; no declaration is needed.- Values have types; names can point at values of any type.
- Multiple assignment and swapping work in a single line.
- Use descriptive
snake_casenames and avoid reserved words.
Quiz: Variables