Skip to content
Variables and Data Types
step 1/8

Reading — step 1 of 8

Learn

~3 min readGetting Started

Imagine you're moving into a new apartment. You have boxes everywhere — one labeled "kitchen stuff," another labeled "winter clothes," another labeled "important documents." Variables are your program's labeled boxes. They let you store a value, give it a name, and use that name to reach the value whenever you need it.

Creating a variable

In Python, you create a variable by assigning a value to a name with =:

python

That single equals sign is called the assignment operator. Read it left-to-right as "the name on the left now refers to the value on the right." From that line onward, anywhere you write name, Python substitutes "Alice". Anywhere you write age, Python substitutes 25.

Unlike many languages, you don't declare the type of a variable. Python figures it out from whatever you assigned. This is called dynamic typing.

The four types you'll use every day

Python has many built-in types, but four cover 90% of beginner code:

python

A fifth special value, None, represents "no value yet" — useful as a placeholder.

Use type() to ask Python what type a value is:

python

Reassignment

A variable doesn't lock to its first value. You can reassign:

python

The variable always reflects its most recent assignment. The old value is forgotten.

Naming rules

Python is strict about what's a valid variable name:

  • ✓ Letters, digits, underscores. Case sensitive: Age and age are different variables.
  • ✓ Must start with a letter or underscore — name, _name, name1 are fine.
  • Cannot start with a digit: 1name is a syntax error.
  • Cannot be a Python keyword like if, for, class, True, None. Try print(False) and Python is happy. Try False = 0 and you get SyntaxError.
  • No spaces or hyphens. user-name looks like subtraction; user name looks like two separate things.

Style: snake_case

The Python community has a strong convention: variable names are lowercase with underscores between words. This is called snake_case.

python

Following the convention makes your code feel native to other Python programmers. Mixing styles makes it look amateur.

Names should describe meaning

python

A variable named n is fine for a tiny loop counter. A variable named n for the user's bank balance is a future bug. Give names that describe what the value MEANS, not just what shape it has.

Common mistakes

  • Using = to compare: if age = 18: is a syntax error. Comparison uses ==.
  • Using a variable before assigning it: print(age) before age = 25 raises NameError.
  • Assuming the type from the value's appearance: "42" (a string) and 42 (an int) look similar but behave very differently. "42" + 1 is an error; 42 + 1 is 43.

Discussion

Ask a question, share an insight, or help someone who’s stuck.

Sign in to post a comment or reply.

Loading…

Variables and Data Types — Python Fundamentals