Learn by reading through in order

Variables and Data Types

Get started with Python variables and the basic data types — every example is runnable directly in your browser.

What is a variable?

A variable is a named box you can put data into. For example, write x = 10 and the integer 10 goes into x.

You can later read the value back through the same name, or overwrite it with a new one.

How variables relate to values
Variable name(x)Value(10)Memoryreferencestore

A variable name references a value, and the value lives in memory

Let's try it in the console. Type x = 10 and print(x) into the console on the right and run it.

Python Editor

Run code to see output

Did 10 show up on the right? That's the output of print(x).

When you call print(variable), it displays whatever's inside the variable on the screen.

On the other hand, trying to use a variable you haven't assigned yet throws a NameError. Python is telling you that no variable by that name exists.

You always have to assign a variable before you use it.

Let's see the error in the console.

Python Editor

Run code to see output

What is a type?

Every value you put in a variable has a type. A type is like a label that says what kind of data this is.

For example, 10 has the type integer (int) and "hello" has the type string (str).

Integer type (int)

int is the type for integers. Any number without a decimal point is treated as an int.

The key feature of int is that you can perform arithmetic — addition, subtraction, multiplication, and division — directly on it.

Pass it to type() and you'll see <class 'int'>, confirming it's an int.

Basics of int
10(numeric literal)int10 + 5= 1510 * 3= 30<class 'int'>type is setaddmultiplyshow type
a = 10
b = 3

print(a + b)   # 13 (addition)
print(a - b)   # 7  (subtraction)
print(a * b)   # 30 (multiplication)
print(a // b)  # 3  (integer division: drops the remainder)
print(a % b)   # 1  (modulo: division remainder)

print(type(a)) # <class 'int'>

You're given total_minutes = 130 (a total in minutes).

① Use integer division // to figure out how many hours that is, and modulo % to figure out the leftover minutes. Display each value with print().

② Use type() to display the type of total_minutes.

Python Editor

Run code to see output

String type (str)

str is the type for strings. Anything wrapped in single quotes '...' or double quotes "..." becomes a str.

You can concatenate strings with +, or get the length with len().

Wrap a number in quotes like "10" and it becomes a str — you can't do arithmetic on it as-is.

Basics of str
"hello"string literalstr"hello" + "!"= "hello!"len("hello")= 5type is setconcatlength

A string literal becomes a str, and you can use it for concatenation and length

greeting = "hello"
name = "Alice"

print(greeting + ", " + name + "!") # hello, Alice!
print(len(greeting))                 # 5 (length)

# Note: "10" is a str, so you can't do math on it
num_str = "10"
# print(num_str + 5)  # TypeError!
print(int(num_str) + 5)              # 15 (works once you convert with int())

print(type(greeting))                # <class 'str'>

You're given name = "Alice" and score = "95".

① Use + to display "Alice's score is 95 points.".

② Use len() to display the length of name.

Python Editor

Run code to see output

Mixing different types

When the types differ, what you can do with them changes too. Two integers can be added together, but trying to add an integer and a string throws a TypeError.

Let's see in the code below what happens when you mix int and str.

age = 25          # int
name = "Alice"    # str

# int + int is fine
print(age + 10)          # 35

# str + str is fine (concatenation)
print(name + "!")        # Alice!

# int + str throws an error
# print(age + name)      # TypeError: unsupported types for __add__: 'int', 'str'

# str() converts so you can concatenate
print(str(age) + " years old")   # 25 years old

Run the code and confirm that you get a TypeError.

Python Editor

Run code to see output

Declaring and assigning variables

Python uses what's called dynamic typing, so unlike Java or C, you don't need to declare a type up front like int x;.

You define a variable just by using = to assign the value on the right to the name on the left.

And once a variable has a value, you can freely reassign it to a new one.

Dynamic typing vs static typing
Dynamictyping(Python)x = 10→ intx = 'hello'→ strStatictyping(Java / C)int x = 10type declaration requiredx = 'hello'compile errorassignreassign OKdeclare typetype mismatch

Python decides types at runtime (dynamic), while Java and C fix them at compile time (static)

Here's an example of assigning and reassigning values. In Python, you can assign without specifying a type, and you can reassign as much as you want.

# Assigning to variables
name = "Alice"
age = 25

# Reassigning (overwriting the value)
age = 26

# Assign different values to multiple variables at once (in a single line)
x, y, z = 1, 2, 3

Do the following three steps in order, displaying each with print().

① Assign "Tokyo" to the variable city and display it.

② Reassign city to "Osaka" and display it (confirm that you can overwrite the same variable).

③ Assign 10, 20, 30 to a, b, c at the same time and display all three together.

Python Editor

Run code to see output

Variable naming rules

You can name variables however you like, but there are a few rules to follow.

- Allowed characters are letters (a-z, A-Z), digits (0-9), and the underscore (_)

- The first character must be a letter or an underscore (you can't start with a digit)

- Names are case-sensitive (age and Age are different variables)

Variable nameOK / NGReason
user_nameOKLetters and underscores
age2OKStarts with a letter; digits are fine after that
_totalOKStarting with an underscore is allowed
2nd_userNGCan't start with a digit
user-nameNGHyphens aren't allowed
user nameNGNo spaces allowed

On top of that, you can't use Python's reserved words (keywords) — words the language has already given a meaning. There are about 35 of them, including 'for', 'if', 'class', 'return', 'True', 'None', and 'import'. Try to use one as a variable name and you'll get a SyntaxError.

Let's see what happens when you run a variable name that breaks the rules.

Python Editor

Run code to see output

Constants — writing values that don't change

Values that you set once and never change are called constants, and the Python convention is to write them in all caps with underscores.

If the number 20 just shows up in the middle of your code, a reader has no idea why it's 20 (a mystery number like this is called a magic number). Name it as a constant up front — LEGAL_AGE = 20 — and the meaning is obvious at a glance, plus when you want to change the value you only have to edit that one line.

# Constants use all caps + underscores
LEGAL_AGE = 20
MAX_RETRY = 3
PI = 3.14159

print(f"Legal age is {LEGAL_AGE}")
print(f"Max retries: {MAX_RETRY}")
print(f"Pi is about {PI}")

Python has no real constants

Unlike C or Java, Python has no built-in way to forbid reassignment. Write LEGAL_AGE = 20 and then LEGAL_AGE = 25, and there's no error — the value just changes. Think of all-caps as a convention between programmers that says "please don't change this".

Let's calculate a tax-included price using a constant.

① Assign 0.1 to the constant TAX_RATE (the sales tax rate).

② Assign 980 to price.

③ Calculate the tax-included price (price × (1 + TAX_RATE)) and display it with print().

Python Editor

Run code to see output

Checking and converting types

The type() function tells you a variable's data type (what kind of data it holds). And built-in functions like int() and str() (functions that come with Python out of the box) let you convert a value to a different type — this is called type conversion, or casting.

For example, if you want to do math on a number that came in as a string from user input, you have to convert it to an int with int().

Here's an example of checking types and converting between them.

# Check the type
x = 42
print(type(x))        # <class 'int'>
print(type("hello"))  # <class 'str'>

# Type conversion
num_str = "100"
num_int = int(num_str)   # str → int
back_to_str = str(num_int)  # int → str

print(num_int + 50)  # 150
Type conversion flow
"100"strint()convert100intstr()convert"100"strpassstr→intpassint→str

You're given a price as a string: price_str = "1980".

① Convert it to an int with int(), then calculate and display the tax-included price (10% sales tax added).

② Use type() to display the type before (price_str) and after (price_int) the conversion.

Python Editor

Run code to see output

ValueError when conversion isn't possible

Pass a string that can't be read as a number to int() or float(), and you get a ValueError. For example, int("abc") and float("hello") both error out. When you're converting things like user input, wrap it in try / except to handle the exception.

Run the code and confirm that you get a ValueError. Handling a ValueError properly requires exception handling.

Python Editor

Run code to see output

In this article you learned how to use variables, the basics of int and str, and how dynamic typing works.

From checking types with type() to type conversion with int() and str(), and even the ValueError that pops up when conversion fails — you've got a complete foundation in Python's data types.

QUIZ

Knowledge Check

Answer each question one by one.

Q1Which of the following can't be used as a variable name?

Q2What does this code output?
x = str(3.14)
print(type(x))

Q3What does this code output?
x = "10"
print(int(x) + 5)