ODOO PYTHON BOOTCAMP / LECTURE 1.2
Python data types,
with everyday examples.
Programs work with different kinds of information: words, numbers, yes-or-no answers, and groups of values. Python gives each kind its own type.
01 / DIFFERENT VALUES, DIFFERENT JOBS
What kind of value is this?
Think about a book in a library. Its title is made of words. Its number of copies is a whole number. Its price may include cents. Whether it is available can be answered with yes or no.
Python treats these as different kinds of values. It calls the kind of a value its type. A type tells Python what the value is and what you can do with it. You can join two pieces of text. You can add two numbers. You cannot sensibly add a title to a number of copies.
Text / str
"The Hobbit"
A title or author’s name.
Whole number / int
8
A count of copies.
Decimal number / float
14.99
A measured or approximate value.
Yes or no / bool
True
Whether a copy is available.
True and False, with capital first letters. We’ll look at when each type is useful below.Here are all four values together. Python can show the type of a value with type().
title = "The Hobbit"
copies = 8
price = 14.99
is_available = True
print(type(title)) # <class 'str'>
print(type(copies)) # <class 'int'>
print(type(price)) # <class 'float'>
print(type(is_available)) # <class 'bool'>Read the examples aloud: title is text; copies is eight; is_available is true. The name tells us what the value means. The type tells Python how to work with it.
Quick check · Which type would you use?
A book’s title? Text. The number of pages? A whole number. Whether the book has been returned? A Boolean.
Ask what the information means, not just what the characters look like.
02 / GIVE VALUES READABLE NAMES
Variables let you refer to a value later.
A variable is a name you choose for a value. In copies = 8, the name is copies and the value is 8. A single equals sign assigns a value to a name. It does not ask whether two values are equal.
book_title = "The Hobbit"
copies = 8
print(book_title)
print(copies)
copies = 7 # There is now one fewer copy.
print(copies)The output is the title, then 8, then 7. On the last assignment, Python gives the name copies a new value. The earlier number 8 has not been changed.
copies = 7, what does copies refer to?Current value
7
copies says more than x; book_title says more than thing.Use names that describe the information. Python convention uses lowercase words separated by underscores: book_title, is_available, borrower_name. Names are case-sensitive: title and Title are different names.
A line beginning with # is a comment for people reading the code. Indentation means spaces at the start of a line. Python uses indentation to show which lines belong together. We’ll use it for decisions in the next lecture.
Predict · What will display_name print?
member_name = "Amina" display_name = member_name member_name = "Sam" print(display_name)
It prints Amina. The second line gives display_name the current value of member_name. Changing member_name later does not change display_name.
03 / WORK WITH TEXT
Strings hold words and identifiers.
A string is Python’s name for a piece of text. Put text inside matching single or double quotes. Use strings for titles, names, email addresses and codes such as ISBNs.
title = "The Hobbit"
author = 'J. R. R. Tolkien'
isbn = "978-0-547-92822-7"
print(title)
print(isbn)An ISBN looks like a number, but it identifies a book. You do not add ISBNs together. Keeping it as text also preserves any leading zeros. Use a number when you need arithmetic, such as counting pages.
Join text and find its length.
The + operator joins strings. len() counts the characters in a string. An f-string is an easy way to include a value inside a sentence: put an f before the opening quote and put the variable in braces.
title = "The Hobbit"
author = "J. R. R. Tolkien"
print(title + " by " + author)
print(len(title))
print(f"{title} was written by {author}.")The f-string keeps the sentence readable. It works with numbers as well: f"Copies: {8}" displays Copies: 8. By contrast, "Copies: " + 8 causes a TypeError because + cannot join text and an integer.
Pick out part of a string.
Python counts string positions starting at zero. In "Hobbit", the first character is at position zero. A slice such as [0:3] starts at zero and stops before position three, so it returns the first three characters.
"Hobbit"The first position is zero.0
H
1
o
2
b
3
b
4
i
5
t
title[0] is "H"; title[:3] is "Hob". A slice stops just before its end position.String methods give you a new string. For example, .strip() removes spaces from the beginning and end. It leaves the original string alone:
raw_title = " The Hobbit "
title = raw_title.strip()
print(title) # The Hobbit
print(raw_title) # The HobbitQuick check · Why keep the ISBN in quotes?
An ISBN identifies a book; it is not a quantity to add or multiply. Treating it as text preserves its exact characters and leading zeros.
04 / WORK WITH NUMBERS AND YES/NO VALUES
Use numbers for arithmetic.
An int is a whole number, such as 8 copies. A float can include a decimal part, such as 4.5 hours. Python can add, subtract and multiply numbers. Division with / may give a decimal result.
copies = 8
returned = 1
remaining = copies - returned
print(remaining) # 7
print(remaining * 2) # 14
print(7 / 2) # 3.5For prices, a decimal-looking Python float may store a tiny approximation. Python’s Decimal can represent decimal amounts for a simple standalone example:
from decimal import Decimal
price = Decimal("0.10")
total = price * 3
print(total) # 0.30Booleans answer yes-or-no questions.
A bool can be True or False. A statement such as copies > 0 compares two values and produces one of these answers. Two equals signs, ==, compare values. One equals sign, =, assigns a value.
copies = 8
is_available = copies > 0
print(is_available) # True
print(copies == 8) # True
print(copies == 0) # FalsePython also treats some values as “false” in a condition: zero, an empty string, an empty list and None. None means no value was supplied. It is different from zero or an empty string.
print(bool(0)) # False
print(bool("")) # False
print(bool("False")) # True: this is text with six characters
print(bool(None)) # False
returned_at = None
print(returned_at is None) # True: no return date yetThe text "False" is not the Boolean value False. It is a non-empty string, so Python treats it as true in a condition. Use is None when you mean “no value”; use == when you want to compare ordinary values.
Predict · Is "False" true or false?
bool("False") is True. Python checks whether the string is empty; it does not read the word as an instruction. This is why the type of a value matters.
05 / KEEP VALUES TOGETHER
Lists and dictionaries hold groups of values.
So far, each variable has held one value. Often you need several values together. Python has different kinds of collections. Start with two you will use often: a list and a dictionary.
A list keeps an ordered group.
Write a list with square brackets. The values stay in order, and you can use their positions to get one back. A list can hold repeated values.
titles = ["The Hobbit", "Dune", "The Hobbit"]
print(titles[0]) # The Hobbit
print(len(titles)) # 3
titles.append("1984") # Add a title at the end.
print(titles).append() changes the list by adding an item at the end. The list still remembers the order in which the titles were added.
A dictionary gives values names.
Write a dictionary with curly braces. Each entry has a key and a value. The key is the name you use to look up the value. This is useful when several details belong to one book.
book = {
"title": "The Hobbit",
"author": "J. R. R. Tolkien",
"copies": 8,
}
print(book["title"])
print(book["copies"])
book["copies"] = 7 # Update the value for this key.
print(book["copies"])Use square brackets with a key when that key should be present. If it is missing, Python raises a KeyError. book.get("publisher") returns None when no publisher key is present. Choose based on whether the detail is required or optional.
List
["The Hobbit", "Dune"]
Use a list when order or position matters.
Dictionary
{"title": "The Hobbit", "copies": 8}
Use a dictionary when each value has a name.
Two more collections you will meet.
A tuple is written with parentheses: ("basic", 3). You can use positions to read its values, but you cannot replace an item after creating it. Tuples are useful for small, fixed groups of values.
A set is a collection of unique values: repeated items are kept once. Use a set when you need to know which values are present, and do not need their order.
policy = ("basic", 3)
print(policy[0]) # basic
seen_titles = {"The Hobbit", "Dune", "The Hobbit"}
print(len(seen_titles)) # 2: repeats appear once in a setQuick check · Which collection fits?
Reading list in order? A list. Details for one book, such as title and author? A dictionary. Unique genres? A set. Start by asking what you need the collection to do.
06 / PUT THE IDEAS TOGETHER
Make a short book record.
Let’s create a small record for a book. We’ll use a dictionary because the book has several named details, and a list because we want an ordered reading list.
data_types_lab.pybook = {
"title": "The Hobbit",
"author": "J. R. R. Tolkien",
"copies": 8,
"is_available": True,
}
reading_list = [book["title"], "Dune"]
print(f"{book['title']} by {book['author']}")
print(f"Copies: {book['copies']}")
print(f"Available: {book['is_available']}")
print(f"Next on the list: {reading_list[1]}")
assert book["title"] == "The Hobbit"
assert book["copies"] == 8
assert book["is_available"] is True
assert reading_list == ["The Hobbit", "Dune"]
print("All four checks passed.")Before running it, guess each line of output. Then save the example as data_types_lab.py and run python3 data_types_lab.py. The assertions check that the values are what we expect. If one is wrong, Python stops and points to the failed check.
Download the standalone Python lab → This file matches the example above.
Reveal · Expected output
The Hobbit by J. R. R. Tolkien Copies: 8 Available: True Next on the list: Dune All four checks passed.
Change copies from 8 to 7 and run the program again. The record now holds seven copies; the rest of the program still works. That is one reason a dictionary key such as "copies" is easier to understand than remembering which list position holds the count.
Where this appears in Odoo
Odoo uses Python classes to define models and fields. A model field can hold text, a whole number, a decimal number or a Boolean value. The Odoo ORM also uses dictionaries of named values when creating or updating records. A book’s dictionary above is a Python learning example; it does not create a database record by itself.
In the next lessons, we’ll add decisions and functions, then use those ideas as we begin working with Odoo models. For now, make sure you can explain the difference between a string, an integer, a Boolean, a list and a dictionary.
Use conditions to make a program choose what to do.