Module 2 · Python for Beginners
Variables and Data Types
Store values in variables, name them well, know Python's main data types, check a value's type, and convert between types.
About 35 minutes
Open in ColabEvery example as a notebook you can run, edit and save to your Google Drive.
Variables
A variable is a name that stores a value, so you can use it later. Create one with =:
Edit the code and press Run (Ctrl + Enter). Examples on this page share their variables, like cells in a notebook.
Output
Ifeoma
20Read = as "is set to", not "equals": age = 20 means "set age to 20". The name goes on the left, the value on the right.
Once a variable exists, use its name anywhere you'd use the value:
Edit the code and press Run (Ctrl + Enter). Examples on this page share their variables, like cells in a notebook.
Output
10000Changing a variable
A variable holds one value at a time. Assign again and the old value is replaced:
Edit the code and press Run (Ctrl + Enter). Examples on this page share their variables, like cells in a notebook.
Output
5000
3200You can use a variable's current value to work out its new one. This is very common:
Edit the code and press Run (Ctrl + Enter). Examples on this page share their variables, like cells in a notebook.
Output
3200Python works out the right-hand side first (5000 − 1800), then stores the answer in balance. There's a shortcut for it, balance -= 1800, and the same for the other operators: +=, *=, /=.
Naming variables
| Rule | Allowed | Not allowed |
|---|---|---|
| Letters, numbers and underscores only | first_name, total2 | first-name, first name |
| Can't start with a number | course2 | 2course |
| Capitals matter | Age and age are different variables | |
| Not a Python keyword | class_name | class, if, for |
And by convention:
- use lowercase with underscores (
monthly_budget), called snake_case; - choose names that say what's inside:
transport_costbeatsxortc.
Several at once
You can assign several variables in one line, matching names to values in order:
Edit the code and press Run (Ctrl + Enter). Examples on this page share their variables, like cells in a notebook.
Output
Ibadan OyoData types
Every value has a type, which decides what you can do with it. You can add two numbers, but you can't sensibly multiply two names. Python's main types:
| Type | Name in Python | Examples | Used for |
|---|---|---|---|
| text | str (string) | "Lagos", 'ECO 201', "" | names, codes, messages |
| whole number | int (integer) | 42, -7, 0 | counts, IDs, ages |
| decimal number | float | 3.75, -0.5, 2.0 | prices with kobo, averages |
| true or false | bool (boolean) | True, False | yes/no answers |
| nothing | NoneType | None | "no value yet" |
Check any value's type with type():
Edit the code and press Run (Ctrl + Enter). Examples on this page share their variables, like cells in a notebook.
Output
<class 'str'>
<class 'int'>
<class 'float'>
<class 'bool'>
<class 'NoneType'>Strings
Text goes in quotes, single or double; both work, as long as they match. Use double quotes when the text contains an apostrophe:
Edit the code and press Run (Ctrl + Enter). Examples on this page share their variables, like cells in a notebook.
Output
Economics
I'm in 200 levelNumbers: int and float
A number with a decimal point is a float, even if it ends in .0:
Edit the code and press Run (Ctrl + Enter). Examples on this page share their variables, like cells in a notebook.
Output
<class 'int'>
<class 'float'>Don't use commas inside numbers: 60,000 isn't sixty thousand to Python. Write 60000, or use an underscore to make it readable: 60_000.
Edit the code and press Run (Ctrl + Enter). Examples on this page share their variables, like cells in a notebook.
Output
60000Booleans
True and False (capital first letter, no quotes) are answers to yes/no questions. You'll get them from comparisons:
Edit the code and press Run (Ctrl + Enter). Examples on this page share their variables, like cells in a notebook.
Output
True
FalseYou'll use booleans all the time in the lesson on conditions.
None
None means "no value". It's what you store when a value isn't known yet:
Edit the code and press Run (Ctrl + Enter). Examples on this page share their variables, like cells in a notebook.
Output
NoneConverting between types
Values often arrive as the wrong type, especially numbers stored as text (from a form, a file or a spreadsheet). Text that looks like a number doesn't behave like one:
Edit the code and press Run (Ctrl + Enter). Examples on this page share their variables, like cells in a notebook.
Output
55
10With text, + joins; with numbers, it adds. Convert with these functions:
| Function | Converts to | Example | Result |
|---|---|---|---|
int() | whole number | int("42") | 42 |
float() | decimal | float("3.5") | 3.5 |
str() | text | str(2500) | "2500" |
bool() | true or false | bool(0) | False |
Edit the code and press Run (Ctrl + Enter). Examples on this page share their variables, like cells in a notebook.
Output
50000
9
7.0
2026 budgetNote that int(9.99) gives 9: it cuts off the decimals, it doesn't round. Use round(9.99) to round.
Conversions only work when they make sense:
int("forty")Output
ValueError: invalid literal for int() with base 10: 'forty'A ValueError means the value can't be converted.
Putting values into text
To mix text and numbers in one message, use an f-string: put f before the opening quote, and variables inside {curly brackets}:
Edit the code and press Run (Ctrl + Enter). Examples on this page share their variables, like cells in a notebook.
Output
Musa is in 300 levelWithout an f-string, joining text and a number with + fails, because they're different types:
print("Level: " + level)Output
TypeError: can only concatenate str (not "int") to strFix it with an f-string, f"Level: {level}", or by converting, "Level: " + str(level). You'll learn much more about f-strings in the lesson on text.
Getting input from the user
input() pauses your program and waits for someone to type, then gives you what they typed, always as text:
name = input("What is your name? ")
age = int(input("How old are you? "))
print(f"Hello {name}, next year you'll be {age + 1}")Notice int(...) around the second input: without it, age would be text and age + 1 would fail. In Colab, a box appears under the cell for you to type into.
Summary
| You want to... | Write |
|---|---|
| store a value | name = "Ifeoma" |
| update a value | balance = balance - 1800 or balance -= 1800 |
| check a type | type(value) |
| text to a number | int("42"), float("3.5") |
| a number to text | str(2500) |
| text with values in it | f"{name} is {age}" |
| ask the user | input("Question? ") (gives text) |
Try it
Practice
You start the month with balance = 60000. You spend 12,500 on transport and 28,000 on food, updating balance after each. What is balance at the end?
Practice
What does int("45000") + 5000 give?
Practice
What does int(7.9) give?
Task
6 minWrite code that stores your name, course, level and number of courses this semester in four variables (at least one text and one number), then prints one sentence about you with an f-string, for example Ifeoma is a 200 level Economics student taking 9 courses. Run it in Colab, then paste your code here.
Your work is checked for
- At least four variables assigned with =
- Text values in quotes
- A number stored without quotes
- Prints with an f-string that uses your variables
Earn your badge
Take the module check
Questions on this module. Pass and you earn the Python Variables badge, free.
Create a free account to earn the badge