Skip to content

Variables and Data Types

💡
Before you start

You need Python installed, and to know how to run a .py file. If python3 --version in a terminal prints a version number, you are ready. If it does not — or if you have never opened a terminal — do Getting Started with Python first; it installs Python and runs your first program, and takes about fifteen minutes. Nothing else is needed: no account, no payment, no extra software.

What Are Variables?

A variable is a named container that stores a value. Think of it as a labeled box where you put data that your program needs to remember and use later.

name = "Alice"
age = 25
height = 1.68

In Python, you create a variable simply by assigning a value to a name using the = sign. No special keywords or type declarations needed.

💡
Variable naming rules

Variable names must start with a letter or underscore, can contain letters, numbers, and underscores, and are case-sensitive (Name and name are different variables). Use descriptive names like user_age instead of x.

Strings

Strings are sequences of characters, used for text. They're enclosed in quotes — either single (') or double ("):

greeting = "Hello, World!"
name = 'Alice'
message = "It's a beautiful day"

String Operations

# Concatenation (joining strings)
first = "Hello"
second = "World"
combined = first + " " + second    # "Hello World"

# Repetition
laugh = "ha" * 3                   # "hahaha"

# Length
length = len("Python")             # 6

# Accessing characters (0-indexed)
word = "Python"
first_char = word[0]               # "P"
last_char = word[-1]               # "n"

f-Strings (Formatted Strings)

The modern way to embed variables inside strings:

name = "Alice"
age = 25
print(f"My name is {name} and I am {age} years old.")
# Output: My name is Alice and I am 25 years old.

Numbers

Python has two main number types:

Integers (int)

Whole numbers without decimal points:

age = 25
year = 2026
negative = -10
big_number = 1_000_000    # underscores for readability

Floats (float)

Numbers with decimal points:

height = 1.68
temperature = -3.5
pi = 3.14159

Arithmetic Operations

a = 10
b = 3

print(a + b)     # 13    Addition
print(a - b)     # 7     Subtraction
print(a * b)     # 30    Multiplication
print(a / b)     # 3.333 Division (always returns float)
print(a // b)    # 3     Integer division (rounds down)
print(a % b)     # 1     Modulus (remainder)
print(a ** b)    # 1000  Exponentiation (power)
⚠️
Division always returns a float

10 / 2 returns 5.0 (not 5). Use // for integer division if you need a whole number result.

Booleans

Booleans represent truth values — either True or False:

is_student = True
is_admin = False

# Comparison operators return booleans
print(5 > 3)       # True
print(10 == 20)    # False
print(5 != 3)      # True
print(5 >= 5)     # True

Boolean Operations

a = True
b = False

print(a and b)     # False (both must be True)
print(a or b)      # True  (at least one must be True)
print(not a)       # False (inverts the value)

Type Checking and Conversion

Use type() to check what type a variable is:

print(type("hello"))    # <class 'str'>
print(type(42))         # <class 'int'>
print(type(3.14))       # <class 'float'>
print(type(True))       # <class 'bool'>

Convert between types:

# String to integer
age_str = "25"
age_num = int(age_str)      # 25

# Integer to string
count = 42
count_str = str(count)      # "42"

# String to float
price = float("19.99")     # 19.99

# Float to integer (truncates, doesn't round)
whole = int(3.7)            # 3
⚠️
Invalid conversions cause errors

int("hello") will crash your program with a ValueError. Only convert strings that actually contain valid numbers.

User Input

Get input from the user with the input() function:

name = input("What is your name? ")
print(f"Hello, {name}!")

# input() always returns a string, so convert for numbers:
age = int(input("How old are you? "))
print(f"In 10 years you'll be {age + 10}.")

Now Do It Yourself: Five Steps

Everything above is the idea. This part is the doing. Follow it on your own machine and you will have written, run and debugged a real Python program by the end — and every error shown below is the exact text Python prints, not a paraphrase.

1
Confirm Python is already on your computer

Go: open a terminal. On Linux press Ctrl + Alt + T; on macOS open Terminal from Applications → Utilities; on Windows open PowerShell from the Start menu.

Do: type python3 --version and press Enter.

You should see: a line like Python 3.12.3. Any version starting with 3. is fine for everything on this page.

If not: if you get command not found, try python --version instead — on Windows the command is usually python, with no 3. If both fail, Python is genuinely not installed: download it from python.org/downloads, and on Windows tick Add python.exe to PATH on the first screen of the installer. Skipping that tickbox is the single most common reason the command still fails afterwards.

2
Create your first variable, live

Go: in the same terminal, type python3 on its own and press Enter. The prompt changes to >>>, which means Python is now listening.

Do: type name = "Alice" and press Enter, then type print(name) and press Enter.

You should see: Alice on the next line. You just stored a value and read it back.

If not: if you see NameError: name 'Alice' is not defined, you left out the quotation marks. Without quotes Python thinks Alice is another variable's name rather than text. Type it again as name = "Alice". Python 3.12 even guesses at your intent in that message — ignore the guess, add the quotes.

3
Move it into a real file you can keep

Go: leave the interactive prompt by typing exit() and pressing Enter. Then create a file called hello.py in your home folder, using Notepad on Windows, TextEdit on macOS, or Text Editor on Linux. In Notepad's Save dialog set "Save as type" to "All Files", and in TextEdit choose Format → Make Plain Text first — otherwise the file is saved as hello.py.txt and will not run.

Do: put these six lines in it, save, then run python3 hello.py in the terminal.

name = "Alice"
age = 25
height = 1.68
print("Name:", name)
print("Age:", age)
print("Height:", height)

You should see: exactly three lines — Name: Alice, Age: 25, Height: 1.68.

If not: python3: can't open file '/tmp/hello.py': [Errno 2] No such file or directory means the terminal is not in the folder where you saved the file — read the path in that message, it tells you where Python looked. Move to the right folder with cd, for example cd ~ if you saved it in your home folder, then run the command again. If your editor saved it as hello.py.txt, rename it; the .py ending must be the last thing in the name.

4
Break it on purpose, so the error never confuses you again

Go: create a second file called oops.py, in the same folder.

Do: put these two lines in it and run python3 oops.py. This one is supposed to fail.

age = "25"
print(age + 1)

You should see: TypeError: can only concatenate str (not "int") to str. Read it as a sentence: age holds the text "25", because it was written in quotes, and Python will not add the number 1 to a piece of text.

If not: if it prints 26 instead, you left the quotes off 25 — then it is a number and the addition works. Put the quotes back and run it again; seeing this error deliberately, once, is worth more than avoiding it by luck for a month. Now fix it properly: change the second line to print(int(age) + 1) and it prints 26. int() converts the text into a number.

5
Ask the person running your program

Go: create a third file called greet.py.

Do: put these three lines in it and run python3 greet.py, answering the two questions.

name = input("What is your name? ")
age = int(input("How old are you? "))
print("Hello,", name, "- next year you will be", age + 1)

You should see: both questions, then for Alice and 25: Hello, Alice - next year you will be 26. Note the int() wrapped around the second input()input() always hands back text, so without it you would meet the same TypeError from step 4.

If not: typing words instead of digits at the age question gives ValueError: invalid literal for int() with base 10: 'twenty'. That is int() saying it cannot turn the word "twenty" into a number. Run it again and type 20. Handling that gracefully instead of crashing is what the exceptions tutorial covers.

🎉
Check yourself before moving on

Without looking back up the page: what would print("7" + 3) do, and what single change makes it print 10? If you can answer both, you have understood the one idea that causes most beginner Python errors — that "7" and 7 are different kinds of thing. Answer: it raises the same TypeError from step 4; print(int("7") + 3) prints 10.

Now do it without the page: write a file that asks for two numbers and prints their total. You will need input(), int() and one print() — the same three moves as step 5, rearranged.

Summary

  • Variables store data using name = value syntax
  • Strings hold text: "hello"
  • Integers hold whole numbers: 42
  • Floats hold decimals: 3.14
  • Booleans hold True/False values
  • Use type() to check types and int(), str(), float() to convert
  • f-strings let you embed variables in text: f"Hello {name}"
🎉
Variables mastered!

You now understand how Python stores and manipulates data. Next up: control flow — making your programs make decisions with if, else, and loops.