Module 1, topic 1, week 1, Tuesday
Python basics and environment setup
Variables, data types, operators, Anaconda and Jupyter
Lesson notebook
The whole lesson as a Jupyter notebook: explanations, every example, practice cells, and exercises with hidden solutions.
topic-01-python-basics.ipynb, 82 KB
Introduction: why Python?
Python is a programming language: a way of giving instructions to a computer using words that look close to normal English. It is the most popular language for Data Science, Machine Learning, and AI for three reasons:
It is easy to read.
Python code looks almost like plain sentences.
It has a huge toolbox.
Free libraries such as pandas, NumPy, and scikit-learn already contain ready-made tools for data work.
It has a huge community.
Whatever problem you get stuck on, someone has already solved it and written about it.
Read these lines out loud. They almost explain themselves:
| Python | In plain English |
|---|---|
| price = 100 | Store 100 under the name price. |
| total = price * 3 | Multiply price by 3 and call the result total. |
| is_expensive = total > 250 | Is total more than 250? Store the yes/no answer. |
| print(total) | Show me total. (It shows 300.) |
This topic has two parts. First, the three building blocks every Python program uses: variables, data types, and operators. Second, how to set up your computer with Anaconda and Jupyter so you can write and run code.
By the end of this lesson you will be able to:
- 1.Create variables, print them, and follow Python's naming rules.
- 2.Recognize the data types int, float, str, bool, None, list, tuple, dict and set, and use the main operations of each.
- 3.Convert values from one type to another, and know when you must.
- 4.Use arithmetic, assignment, comparison, logical, membership and identity operators.
- 5.Install Anaconda, open Jupyter, and run code in notebook cells in the right order.
- 6.Recognize and fix the most common beginner errors.
1Variables
1.1What is a variable?
A variable is a labeled box where you store a piece of information so you can use it later. You choose the label (the name) and put something inside.
name = "Aylin"
age = 20
height = 1.75
is_student = True
print(name)
print(age)
print(height)
print(is_student)Output
Aylin 20 1.75 True
- name"Aylin"
type:
str - age20
type:
int - height1.75
type:
float - is_studentTrue
type:
bool
The = sign here does not mean “equal” like in maths. It means “put the value on the right into the box on the left.”
Read = as “store”, not “equals”: store 20 in age.
1.2Showing values with print() and writing comments
To see what is inside a box, use print(). You can print several values at once by separating them with commas; Python puts a space between them. sep changes that separator, and end changes what is printed at the end of the line (normally a new line).
name = "Aylin"
age = 20
print("Name:", name) # several values, separated by a space
print("Age:", age)
print("Data", "Science", sep="-") # choose the separator
print("Same", end=" ") # do not jump to a new line
print("line")Output
Name: Aylin Age: 20 Data-Science Same line
Anything after a # is a comment. Python ignores it, so you can use it to leave notes for yourself and others, or to switch a line off without deleting it.
# This whole line is a comment. Python skips it.
price = 100 # A comment can also follow code on the same line.
# print(price * 2) <- this line is "commented out", so it does not run
print(price)Output
100
1.3Changing a variable
The content of a box can be replaced at any time. Step through the code and watch the box:
Replacing the value in a box
- 1age = 20
- 2age = 21 # the box now holds 21
- 3age = age + 1 # take the old value, add 1, store it back
What Python remembers
Nothing stored yet. Press “Run next line”.
age = 20
age = 21 # the box now holds 21
age = age + 1 # take the old value, add 1, store it back
print(age)Output
22
1.4Several variables in one line
You can fill several boxes at once, give several boxes the same value, or swap two values without a helper box:
a, b, c = 1, 2, 3 # three boxes in one line
print(a, b, c)
x = y = 0 # the same value into two boxes
print(x, y)Output
1 2 3 0 0
first = "tea"
second = "coffee"
first, second = second, first # swap the two values
print(first, second)Output
coffee tea
1.5Rules for naming variables
| Rule | Works | Does not work |
|---|---|---|
| Names can contain letters, numbers, and underscores (_). | score_2 | score-2 |
| A name cannot start with a number. | score1 | 1score |
| No spaces. Use an underscore instead. | student_name | student name |
| Python is case-sensitive. | Age, age and AGE are three different variables | - |
| Don't use Python's reserved words. | class_name | if, for, class, True |
| Choose meaningful names: price is much better than p. The style lowercase_with_underscores is the Python standard. | price | p (works, but unclear) |
age = 20
Age = 30
AGE = 40
print(age, Age, AGE) # three different variablesOutput
20 30 40
Type a name above, or tap one of the examples.
1.6Python figures out the type for you
In some languages you must announce what kind of data goes in the box. In Python you don't. Python looks at the value and decides by itself. This is why Python is called dynamically typed, and it is one reason beginners find it friendly. The same name can even hold a different type later:
x = 5
print(type(x))
x = "five" # the same name now holds text
print(type(x))Output
<class 'int'> <class 'str'>
Try it yourself
city with any city name and temperature with a decimal number. Print both on one line. Then increase the temperature by 2 and print it again.Show a hint
print(city, temperature). To increase: temperature = temperature + 2.Show the solution
city = "Paris"
temperature = 18.5
print(city, temperature)
temperature = temperature + 2
print(temperature)Output
Paris 18.5 20.5
2Data types
2.1What is a data type?
A data type tells Python what kind of information a value is: a whole number, a piece of text, a yes/no answer, and so on. The type decides what you are allowed to do with the value. You can multiply two numbers, but multiplying two names makes no sense. You can always ask Python for the type with type(), or check it with isinstance():
print(type(20))
print(type(3.5))
print(type("hello"))
print(type(True))
print(type(None))Output
<class 'int'> <class 'float'> <class 'str'> <class 'bool'> <class 'NoneType'>
age = 20
print(isinstance(age, int)) # is age an int?
print(isinstance(age, str)) # is age a str?Output
True False
2.2The basic (single-value) types
| Type | Name | What it holds | Example |
|---|---|---|---|
| int | Integer | Whole numbers | 7, -3, 2026 |
| float | Floating-point number | Numbers with a decimal point | 3.14, -0.5, 2.0 |
| str | String | Text, always inside quotes | "Hello", 'Python' |
| bool | Boolean | Only True or False | True, False |
| NoneType | None | “Nothing here yet” | None |
Guess the type
Value 1 of 8, score 0
What does type(...) say about this value?
7
2.3Numbers: int and float
Mixing an int and a float gives a float, and dividing with / always gives a float. The full list of maths operators is in Part 3.
print(3 + 2) # int + int gives int
print(3 + 2.0) # int + float gives float
print(10 / 5) # / always gives float
print(type(3 + 2.0))Output
5 5.0 2.0 <class 'float'>
Useful functions for numbers
| Function | What it does | Example | Result |
|---|---|---|---|
| abs(x) | Distance from zero | abs(-7) | 7 |
| round(x, n) | Round to n decimals | round(3.14159, 2) | 3.14 |
| min(...), max(...) | Smallest, largest | max(4, 9, 1) | 9 |
| pow(x, y) | x to the power y | pow(2, 5) | 32 |
| divmod(a, b) | Floor division and remainder together | divmod(17, 5) | (3, 2) |
| int(x), float(x) | Convert | int(7.9) | 7 |
print(abs(-7)) # distance from zero
print(round(3.14159, 2)) # round to 2 decimals
print(round(7.6)) # round to a whole number
print(min(4, 9, 1)) # smallest
print(max(4, 9, 1)) # largest
print(pow(2, 5)) # same as 2 ** 5
print(divmod(17, 5)) # (17 // 5, 17 % 5)Output
7 3.14 8 1 9 32 (3, 2)
print(round(2.5)) # rounds to the nearest EVEN number
print(round(3.5))
print(round(4.5))Output
2 4 4
Writing big and small numbers
population = 8_100_000_000 # underscores make long numbers readable
print(population)
distance = 1.5e3 # scientific notation: 1.5 x 10 to the power 3
print(distance)
tiny = 2e-4 # 2 x 10 to the power -4
print(tiny)Output
8100000000 1500.0 0.0002
print(2 ** 100) # Python integers have no size limitOutput
1267650600228229401496703205376
A famous surprise with decimals
print(0.1 + 0.2)
print(0.1 + 0.2 == 0.3)
print(round(0.1 + 0.2, 2))Output
0.30000000000000004 False 0.3
Computers store decimals in binary, so some decimals can't be stored perfectly. It's normal, not a bug, and in practice you round results when displaying them: round(0.1 + 0.2, 2) gives 0.3. For the same reason, avoid comparing decimals with ==.
2.4Strings: working with text
Creating strings
Strings can use single or double quotes. They can be joined, repeated, and combined with variables (all shown below). Use the other kind of quote when your text contains one, and three quotes for text over several lines.
single = 'Hello'
double = "Hello"
with_apostrophe = "It's Python"
many_lines = """Line one
Line two"""
print(single, double)
print(with_apostrophe)
print(many_lines)Output
Hello Hello It's Python Line one Line two
Special characters
| Write | You get |
|---|---|
| \n | a new line |
| \t | a tab (a wide space) |
| \" | a double quote inside double quotes |
| \' | a single quote inside single quotes |
| \\ | one backslash |
print("Name:\tAylin") # \t is a tab
print("First line\nSecond line") # \n starts a new line
print("She said \"hi\"") # \" puts a quote inside quotes
print("C:\\Users\\aylin") # \\ is one backslashOutput
Name: Aylin First line Second line She said "hi" C:\Users\aylin
Positions (indexing) and slices
Each character has a position, starting at 0. Negative positions count from the end. A slice text[start:stop:step] takes a part of the text; the stop position is not included.
word = "Python"
print(word[0]) # first character
print(word[5]) # sixth character
print(word[-1]) # last character
print(word[-2]) # second from the end
print(len(word)) # number of charactersOutput
P n n o 6
word = "Python"
print(word[0:3]) # from 0 up to (not including) 3
print(word[2:]) # from 2 to the end
print(word[:4]) # from the start up to 4
print(word[-3:]) # the last three
print(word[::2]) # every second character
print(word[::-1]) # reversedOutput
Pyt thon Pyth hon Pto nohtyP
Try it: string slicer
| 0 | 1 | 2 | 3 | 4 | 5 |
| P | y | t | h | o | n |
| -6 | -5 | -4 | -3 | -2 | -1 |
>>> word[1:4]
'yth'
The stop position is never included. An empty box means “from the start” or “to the end”.
Joining and repeating
first = "Data"
second = "Science"
print(first + " " + second) # join with +
print("ha" * 3) # repeat with *
print("-" * 20) # a quick divider lineOutput
Data Science hahaha --------------------
Changing case
text = "python for Data Science"
print(text.upper())
print(text.lower())
print(text.title())
print(text.capitalize())
print(text.swapcase())Output
PYTHON FOR DATA SCIENCE python for data science Python For Data Science Python for data science PYTHON FOR dATA sCIENCE
Removing extra spaces
Data typed by people often has spaces at the start or end. strip() removes them:
raw = " Aylin "
print("[" + raw + "]")
print("[" + raw.strip() + "]") # both sides
print("[" + raw.lstrip() + "]") # left side only
print("[" + raw.rstrip() + "]") # right side onlyOutput
[ Aylin ] [Aylin] [Aylin ] [ Aylin]
Replacing text
sentence = "I like cats. Cats are great."
print(sentence.replace("cats", "dogs")) # case-sensitive: "Cats" stays
print(sentence.replace("a", "@", 2)) # only the first 2 matchesOutput
I like dogs. Cats are great. I like c@ts. C@ts are great.
Splitting text into a list, and joining a list into text
csv_line = "apple,banana,cherry"
fruits = csv_line.split(",") # text -> list
print(fruits)
print(" | ".join(fruits)) # list -> text
words = "Data science is fun".split() # split on spaces
print(words)
print(len(words))Output
['apple', 'banana', 'cherry'] apple | banana | cherry ['Data', 'science', 'is', 'fun'] 4
Searching inside text
text = "banana"
print(text.find("an")) # position of the first match
print(text.find("x")) # -1 means "not found"
print(text.index("n")) # like find, but an error if missing
print(text.count("a")) # how many times
print(text.startswith("ban"))
print(text.endswith("na"))
print("nan" in text)Output
1 -1 2 3 True True True
Checking what a string contains
print("2026".isdigit()) # only digits?
print("Aylin".isalpha()) # only letters?
print("abc123".isalnum()) # letters or digits?
print(" ".isspace()) # only spaces?
print("HELLO".isupper())
print("hello".islower())Output
True True True True True True
f-strings: mixing text and values
An f-string has an f before the quotes. Anything in { } is replaced by the variable's value. It is the easiest way to mix text and values, and it can also format numbers.
f"{name} is {age} years old"
{ } is replaced by the value in that variableAylin is 20 years old
name = "Aylin"
score = 87.456
students = 1250
print(f"{name} scored {score} points")
print(f"Rounded: {score:.1f}") # 1 decimal place
print(f"Two decimals: {score:.2f}")
print(f"Total students: {students:,}") # thousands separator
print(f"Next year: {20 + 1}") # any expression worksOutput
Aylin scored 87.456 points Rounded: 87.5 Two decimals: 87.46 Total students: 1,250 Next year: 21
| Inside the braces | Meaning | Example result |
|---|---|---|
| {x} | the value as it is | 87.456 |
| {x:.1f} | 1 decimal place | 87.5 |
| {x:.2f} | 2 decimal places | 87.46 |
| {n:,} | thousands separator | 1,250 |
| {a + b} | any expression | 21 |
Strings cannot be changed in place
A string is immutable: you cannot change one character. You build a new string instead.
word = "Python"
word[0] = "J"Error
TypeError: 'str' object does not support item assignment
word = "Python"
new_word = "J" + word[1:] # build a new string instead
print(new_word)
print(word) # the original is unchangedOutput
Jython Python
String methods at a glance
| Method | What it does |
|---|---|
| len(s) | number of characters (a function, not a method) |
| s.upper(), s.lower() | all capitals, all small letters |
| s.title(), s.capitalize() | Capital Each Word, Capital first letter only |
| s.strip(), s.lstrip(), s.rstrip() | remove spaces at both ends, the left, the right |
| s.replace(old, new) | replace text |
| s.split(sep), sep.join(list) | text to list, list to text |
| s.find(x), s.index(x) | position of x (-1 or an error if missing) |
| s.count(x) | how many times x appears |
| s.startswith(x), s.endswith(x) | True or False |
| s.isdigit(), s.isalpha(), s.isalnum() | only digits, only letters, letters or digits |
Try it yourself
course = "data science". Print it in Title Case, print only the first 4 characters, print its length, and print it with the space replaced by an underscore.Show a hint
.title(), a slice [:4], len() and .replace(" ", "_").Show the solution
course = "data science"
print(course.title())
print(course[:4])
print(len(course))
print(course.replace(" ", "_"))Output
Data Science data 12 data_science
2.5Booleans: True and False
Booleans are the answers to yes/no questions. They are the foundation of decision-making in code (“if it is raining, take an umbrella”), which you will use in the next topic. Every comparison gives a boolean.
is_raining = True
print(is_raining)
print(type(is_raining))
print(5 > 3) # comparisons give booleans
print(10 == 9)Output
True <class 'bool'> True False
Behind the scenes, True counts as 1 and False as 0:
print(True + True) # True counts as 1
print(int(False)) # False counts as 0Output
2 0
Truthy and falsy values
bool() turns any value into True or False. Empty and zero values count as False; everything else counts as True. This becomes important in the next topic, with if.
| Counts as False | Counts as True |
|---|---|
0, 0.0 | 42, -1, 0.5 |
"" (empty string) | "hi", " " (a space is a character) |
[], (), {}, set() (empty collections) | [0] (a list with one item) |
None | - |
print(bool(0), bool(42), bool(-1))
print(bool(""), bool("hi"), bool(" "))
print(bool([]), bool([0]))
print(bool(None))Output
False True True False True True False True False
2.6None: nothing here yet
None is used when a variable exists but doesn't have a value yet. Check for it with is None. Some functions give back None because they do something but return nothing, like print().
result = None
print(result)
print(type(result))
print(result is None)Output
None <class 'NoneType'> True
answer = print("Hello") # print shows text but gives back nothing
print(answer)Output
Hello None
2.7Collection types: many values in one box
Real data usually comes in groups, so Python has types that hold several values:
| Type | Description | Example |
|---|---|---|
| list | An ordered, changeable collection | ["apple", "banana", "cherry"] |
| tuple | An ordered collection that cannot be changed | (10, 20, 30) |
| dict | Pairs of key → value, like a dictionary | {"name": "Aylin", "age": 20} |
| set | A collection with no duplicates and no order | {1, 2, 3} |
fruits = ["apple", "banana", "cherry"]
print(fruits[0]) # apple (counting starts at 0!)
fruits.append("mango") # adds an item to the end
print(len(fruits)) # 4
student = {"name": "Aylin", "age": 20}
print(student["name"]) # Aylin
print({1, 2, 2, 3}) # {1, 2, 3} (duplicates removed)Output
apple
4
Aylin
{1, 2, 3}listordered, can change
| 0 | 1 | 2 |
| "apple" | "banana" | "cherry" |
| -3 | -2 | -1 |
Positions start at 0. Negative positions count from the end: fruits[-1] is the last item.
tupleordered, cannot change
Use a tuple for values that belong together and should stay fixed, like a date or a map position.
dictkey → value pairs
You look things up by key, not by position: student["name"].
setno duplicates, no order
The second 2 is dropped automatically. Handy for finding unique values.
| list | tuple | dict | set | |
|---|---|---|---|---|
| Brackets | [ ] | ( ) | {key: value} | { } |
| Keeps order | Yes | Yes | Yes (order added) | No |
| Can change | Yes | No | Yes | Yes |
| Duplicates | Allowed | Allowed | Keys must be unique | Removed |
| Get an item by | position | position | key | cannot (only check with in) |
2.8Lists
Creating a list
fruits = ["apple", "banana", "cherry"]
numbers = [4, 8, 15, 16, 23, 42]
mixed = ["Aylin", 20, 1.75, True] # different types are allowed
empty = []
print(fruits)
print(len(numbers))
print(mixed)
print(empty)Output
['apple', 'banana', 'cherry'] 6 ['Aylin', 20, 1.75, True] []
Reading items: positions and slices
Lists use the same positions and slices as strings. Python counts from 0.
fruits = ["apple", "banana", "cherry", "mango"]
print(fruits[0]) # first
print(fruits[-1]) # last
print(fruits[1:3]) # slice: positions 1 and 2
print(fruits[:2]) # the first twoOutput
apple mango ['banana', 'cherry'] ['apple', 'banana']
Changing an item
fruits = ["apple", "banana", "cherry"]
fruits[1] = "blueberry" # lists can change
print(fruits)Output
['apple', 'blueberry', 'cherry']
Adding items
fruits = ["apple", "banana"]
fruits.append("cherry") # add to the end
fruits.insert(0, "mango") # add at position 0
fruits.extend(["kiwi", "lime"]) # add several
print(fruits)Output
['mango', 'apple', 'banana', 'cherry', 'kiwi', 'lime']
Removing items
fruits = ["apple", "banana", "cherry", "banana", "kiwi"]
fruits.remove("banana") # removes the FIRST match
print(fruits)
last = fruits.pop() # removes and gives back the last item
print(last, fruits)
second = fruits.pop(1) # removes and gives back position 1
print(second, fruits)
del fruits[0] # deletes position 0
print(fruits)Output
['apple', 'cherry', 'banana', 'kiwi'] kiwi ['apple', 'cherry', 'banana'] cherry ['apple', 'banana'] ['banana']
Searching
nums = [3, 7, 3, 9, 3]
print(7 in nums) # is it in the list?
print(nums.index(9)) # where is it?
print(nums.count(3)) # how many times?Output
True 3 3
Sorting and reversing
sorted(list) gives you a new sorted list and leaves the original alone. list.sort() sorts the list itself.
scores = [72, 95, 58, 88]
print(sorted(scores)) # a NEW sorted list
print(scores) # the original is unchanged
scores.sort() # sorts the list itself
print(scores)
scores.sort(reverse=True) # largest first
print(scores)
scores.reverse() # flip the current order
print(scores)Output
[58, 72, 88, 95] [72, 95, 58, 88] [58, 72, 88, 95] [95, 88, 72, 58] [58, 72, 88, 95]
Counting and maths on a list
scores = [72, 95, 58, 88]
print(len(scores))
print(min(scores), max(scores))
print(sum(scores))
print(sum(scores) / len(scores)) # the averageOutput
4 58 95 313 78.25
Joining and repeating lists
print([1, 2] + [3, 4]) # join two lists
print([0] * 5) # repeat a listOutput
[1, 2, 3, 4] [0, 0, 0, 0, 0]
Lists inside lists
grid = [[1, 2, 3],
[4, 5, 6]]
print(grid[1]) # the second row
print(grid[1][2]) # row 1, position 2Output
[4, 5, 6] 6
Copying a list (a common trap)
a = [1, 2, 3]
b = a # b is the SAME list, not a copy
b.append(4)
print(a) # a changed too!
c = a.copy() # a real copy
c.append(5)
print(a)
print(c)Output
[1, 2, 3, 4] [1, 2, 3, 4] [1, 2, 3, 4, 5]
Making number lists with range()
print(list(range(5))) # 0 up to 5 (not including 5)
print(list(range(2, 10, 2))) # start 2, stop 10, step 2Output
[0, 1, 2, 3, 4] [2, 4, 6, 8]
| Code | What it does |
|---|---|
| lst[i], lst[a:b] | read one item, or a slice |
| lst[i] = x | change an item |
| lst.append(x) | add x at the end |
| lst.insert(i, x) | add x at position i |
| lst.extend(other) | add all items of another list |
| lst.remove(x) | remove the first x |
| lst.pop(), lst.pop(i) | remove and give back the last item, or item i |
| del lst[i] | delete item i |
| x in lst, lst.index(x), lst.count(x) | is it there, where, how many |
| lst.sort(), sorted(lst), lst.reverse() | sort in place, sorted copy, flip |
| len, min, max, sum | size and quick maths |
| lst.copy() | a real, separate copy |
Try it yourself
colors = ["red", "green"]. Add "blue" at the end, put "black" at the start, remove "green", then print the list and its length.Show a hint
append, insert(0, ...), remove and len.Show the solution
colors = ["red", "green"]
colors.append("blue")
colors.insert(0, "black")
colors.remove("green")
print(colors)
print(len(colors))Output
['black', 'red', 'blue'] 3
2.9Tuples
A tuple is like a list that cannot be changed. Use it for values that belong together and should stay fixed, like a point on a map or a date.
point = (3, 4)
colors = ("red", "green", "blue")
single = (5,) # one item needs a comma
not_a_tuple = (5) # just the number 5 in brackets
print(point, colors)
print(type(single))
print(type(not_a_tuple))Output
(3, 4) ('red', 'green', 'blue')
<class 'tuple'>
<class 'int'>colors = ("red", "green", "blue", "green")
print(colors[0])
print(colors[-1])
print(colors[1:3])
print(len(colors))
print(colors.count("green"))
print(colors.index("blue"))Output
red
green
('green', 'blue')
4
2
2Unpacking: one value per name
point = (3, 4)
x, y = point # unpacking: one value per name
print(x)
print(y)Output
3 4
Tuples cannot be changed
colors = ("red", "green", "blue")
colors[0] = "pink"Error
TypeError: 'tuple' object does not support item assignment
print((1, 2) + (3,))
print(("ha",) * 3)Output
(1, 2, 3)
('ha', 'ha', 'ha')2.10Dictionaries
A dictionary stores key → value pairs. You look things up by key, like a word in a real dictionary, not by position.
student = {"name": "Aylin", "age": 20, "course": "Data Science"}
print(student)
print(len(student)) # number of key-value pairsOutput
{'name': 'Aylin', 'age': 20, 'course': 'Data Science'}
3Reading values: [ ] or get()
student = {"name": "Aylin", "age": 20}
print(student["name"]) # by key
print(student.get("age")) # same, but safe
print(student.get("email")) # missing key -> None
print(student.get("email", "not given")) # missing key -> your defaultOutput
Aylin 20 None not given
Square brackets stop with an error when the key is missing. get() gives None (or your default) instead:
student = {"name": "Aylin", "age": 20}
print(student["email"])Error
KeyError: 'email'
Adding and changing
student = {"name": "Aylin", "age": 20}
student["age"] = 21 # change a value
student["email"] = "aylin@example.com" # add a new pair
print(student)
student.update({"age": 22, "course": "AI"}) # change or add several
print(student)Output
{'name': 'Aylin', 'age': 21, 'email': 'aylin@example.com'}
{'name': 'Aylin', 'age': 22, 'email': 'aylin@example.com', 'course': 'AI'}Removing
student = {"name": "Aylin", "age": 20, "email": "aylin@example.com"}
removed = student.pop("email") # remove and give back the value
print(removed)
del student["age"] # delete a pair
print(student)Output
aylin@example.com
{'name': 'Aylin'}Keys, values and pairs
student = {"name": "Aylin", "age": 20}
print(student.keys())
print(student.values())
print(student.items())
print(list(student.keys())) # as a normal listOutput
dict_keys(['name', 'age'])
dict_values(['Aylin', 20])
dict_items([('name', 'Aylin'), ('age', 20)])
['name', 'age']student = {"name": "Aylin", "age": 20}
print("name" in student) # checks the KEYS
print("Aylin" in student) # values are not checked
print("Aylin" in student.values())Output
True False True
Dictionaries can hold lists (and more)
course = {
"title": "Python basics",
"topics": ["variables", "data types", "operators"],
}
print(course["topics"])
print(course["topics"][1])Output
['variables', 'data types', 'operators'] data types
| Code | What it does |
|---|---|
| d[key] | read a value (error if the key is missing) |
| d.get(key, default) | read safely |
| d[key] = value | add a new pair or change a value |
| d.update(other) | add or change several pairs |
| d.pop(key), del d[key] | remove a pair |
| d.keys(), d.values(), d.items() | all keys, all values, all pairs |
| key in d, len(d) | is the key there, how many pairs |
Try it yourself
phone = {"brand": "Nova", "year": 2024}. Add a "price" of 499, change the year to 2025, print the dictionary, then print the "color" using get() with "unknown" as the default.Show a hint
phone[key] = value.Show the solution
phone = {"brand": "Nova", "year": 2024}
phone["price"] = 499
phone["year"] = 2025
print(phone)
print(phone.get("color", "unknown"))Output
{'brand': 'Nova', 'year': 2025, 'price': 499}
unknown2.11Sets
A set keeps each value only once and has no order. It is perfect for removing duplicates and for comparing groups.
nums = {3, 1, 2, 3, 1}
print(nums) # duplicates disappear
empty_set = set() # an empty set
empty_dict = {} # careful: {} is an empty DICT
print(type(empty_set))
print(type(empty_dict))Output
{1, 2, 3}
<class 'set'>
<class 'dict'>grades = [90, 85, 90, 70, 85]
unique = set(grades)
print(len(unique)) # how many different grades
print(sorted(unique)) # as a sorted listOutput
3 [70, 85, 90]
Adding and removing
s = {1, 2, 3}
s.add(4) # add one item
s.add(2) # already there: nothing changes
print(s)
s.remove(1) # remove (error if missing)
s.discard(10) # remove if present (no error)
print(s)Output
{1, 2, 3, 4}
{2, 3, 4}s = {1, 2, 3}
s.remove(10)Error
KeyError: 10
Comparing two sets
Try it: set operations
a = {1, 2, 3, 4} b = {3, 4, 5, 6}
>>> print(a & b)
{3, 4}
intersection: in both
a = {1, 2, 3, 4}
b = {3, 4, 5, 6}
print(a | b) # union: in a OR b
print(a & b) # intersection: in a AND b
print(a - b) # difference: in a but not in b
print(b - a)
print(a ^ b) # symmetric difference: in exactly one of themOutput
{1, 2, 3, 4, 5, 6}
{3, 4}
{1, 2}
{5, 6}
{1, 2, 5, 6}a = {1, 2, 3, 4}
b = {3, 4, 5, 6}
print(a.union(b))
print(a.intersection(b))
print(a.difference(b))
print(3 in a)Output
{1, 2, 3, 4, 5, 6}
{3, 4}
{1, 2}
TrueTry it yourself
{"Ali", "Ben", "Cara"}, on Tuesday: {"Ben", "Cara", "Dana"}. Print, in sorted order, who came on both days and who came at least once.Show a hint
&; at least once is |. Wrap the result in sorted() for a fixed order.Show the solution
monday = {"Ali", "Ben", "Cara"}
tuesday = {"Ben", "Cara", "Dana"}
print(sorted(monday & tuesday)) # came both days
print(sorted(monday | tuesday)) # came at least onceOutput
['Ben', 'Cara'] ['Ali', 'Ben', 'Cara', 'Dana']
2.12Converting between types (type casting)
Sometimes you need to change a value from one type to another:
| Code | Result | What happened |
|---|---|---|
| int("5") | 5 | text → whole number |
| float(3) | 3.0 | whole number → decimal |
| str(10) | "10" | number → text |
| int(3.9) | 3 | cuts off the decimals, does not round |
| list("abc") | ['a', 'b', 'c'] | text → list of characters |
| set([1, 1, 2]) | {1, 2} | list → set, duplicates removed |
| int("3.5") | ValueError | int() cannot read a decimal from text |
print(int("42")) # text -> int
print(float("3.5")) # text -> float
print(str(99)) # number -> text
print(int(7.9)) # float -> int: cuts the decimals
print(float(7)) # int -> floatOutput
42 3.5 99 7 7.0
This matters because data from files and websites often arrives as text (and so does input(), below). The text "5" is not the number 5, and "5" + "5" gives "55", not 10:
Two pieces of text
"5" + "5"
"55"
Text is glued together.
Two numbers
5 + 5
10
Numbers are added.
print("5" + "5") # text: glued together
print(int("5") + int("5")) # numbers: added
print("5" * 3) # text repeatedOutput
55 10 555
print(list("abc")) # text -> list of characters
print(tuple([1, 2, 3])) # list -> tuple
print(set([1, 1, 2])) # list -> set (duplicates removed)
print(list((4, 5))) # tuple -> list
print(dict([("a", 1), ("b", 2)])) # pairs -> dictOutput
['a', 'b', 'c']
(1, 2, 3)
{1, 2}
[4, 5]
{'a': 1, 'b': 2}When conversion fails
print(int("3.5"))Error
ValueError: invalid literal for int() with base 10: '3.5'
print(int(float("3.5"))) # text -> float -> intOutput
3
Reading what the user types: input()
input() waits for the user to type something and press Enter. It always gives back text, so convert it before doing maths. (The output below shows the user typing 19.)
age_text = input("How old are you? ") # input() ALWAYS gives text
age = int(age_text) # convert before doing maths
print("Next year you will be", age + 1)Output
How old are you? 19 Next year you will be 20
3Operators
Operators are symbols that do something with values. In 5 + 3, the + is the operator and 5 and 3 are the values it works on.
3.1Arithmetic operators (maths)
| Operator | Meaning | Example | Result |
|---|---|---|---|
| + | Add | 7 + 2 | 9 |
| - | Subtract | 7 - 2 | 5 |
| * | Multiply | 7 * 2 | 14 |
| / | Divide (always gives a float) | 7 / 2 | 3.5 |
| // | Floor division (drops the decimals) | 7 // 2 | 3 |
| % | Modulus (the remainder) | 7 % 2 | 1 |
| ** | Power | 2 ** 3 | 8 |
a = 17
b = 5
print(a + b) # add
print(a - b) # subtract
print(a * b) # multiply
print(a / b) # divide (always a float)
print(a // b) # floor division
print(a % b) # remainder
print(a ** 2) # powerOutput
22 12 85 3.4 3 2 289
Operator playground
Pick two whole numbers between -1000 and 1000 and an operator. The answer follows Python's rules.
>>> 7 // 2
3
Type of the answer: int
Try : Python rounds down, so the answer is -4, not -3. And : a remainder of 1 means 47 is odd.
Two everyday uses of // and %
The modulus % is handy for checking even and odd numbers: n % 2 == 0 means n is even. Together, // and % split a total into whole units and what is left over:
n = 47
print(n % 2) # remainder after dividing by 2
print(n % 2 == 0) # True would mean "even"Output
1 False
total_minutes = 135
hours = total_minutes // 60 # whole hours
minutes = total_minutes % 60 # what is left over
print(f"{hours} h {minutes} min")Output
2 h 15 min
3.2Order of operations
Order of operations works like in maths: brackets first, then powers, then multiplication and division, then addition and subtraction. When in doubt, add brackets: they make code clearer for everyone.
2 + 3 * 4multiplication first2 + 12then addition14
(2 + 3) * 4brackets first5 * 4then multiplication20
print(2 + 3 * 4) # * before +
print((2 + 3) * 4) # brackets first
print(10 - 4 - 3) # left to right
print(-2 ** 2) # ** before the minus sign!
print((-2) ** 2)Output
14 20 3 -4 4
| Order | Operators |
|---|---|
| 1 (first) | ( ) |
| 2 | ** |
| 3 | -x (a minus sign in front) |
| 4 | * / // % |
| 5 | + - |
| 6 | == != < > <= >= in not in is is not |
| 7 | not |
| 8 | and |
| 9 (last) | or |
3.3Assignment operators (store and update)
These are shortcuts for updating a variable:
| Operator | Same as | Example (x starts at 10) |
|---|---|---|
| = | store | x = 10 |
| += | x = x + n | x += 5 gives 15 |
| -= | x = x - n | x -= 3 gives 7 |
| *= | x = x * n | x *= 2 gives 20 |
| /= | x = x / n | x /= 4 gives 2.5 |
| //= | x = x // n | x //= 3 gives 3 |
| %= | x = x % n | x %= 3 gives 1 |
| **= | x = x ** n | x **= 2 gives 100 |
Updating x with assignment shortcuts
- 1x = 10
- 2x += 5 # same as x = x + 5
- 3x -= 3 # same as x = x - 3
- 4x *= 2 # same as x = x * 2
- 5x /= 4 # same as x = x / 4
What Python remembers
Nothing stored yet. Press “Run next line”.
x = 10
x += 5 # x = x + 5
print(x)
x -= 3 # x = x - 3
print(x)
x *= 2 # x = x * 2
print(x)
x /= 4 # x = x / 4 (now a float)
print(x)Output
15 12 24 6.0
n = 7
n //= 2 # n = n // 2
print(n)
n **= 3 # n = n ** 3
print(n)
n %= 5 # n = n % 5
print(n)
greeting = "Hello"
greeting += ", Aylin" # += also works on text
print(greeting)Output
3 27 2 Hello, Aylin
3.4Comparison operators (ask a question, get True or False)
| Operator | Meaning | Example | Result |
|---|---|---|---|
| == | Equal to | 5 == 5 | True |
| != | Not equal to | 5 != 3 | True |
| > | Greater than | 3 > 5 | False |
| < | Less than | 3 < 5 | True |
| >= | Greater than or equal | 5 >= 5 | True |
| <= | Less than or equal | 4 <= 3 | False |
age = 18
Stores. Puts 18 into the box called age.
age == 18
Asks. Is age 18? The answer is True or False.
print(5 == 5)
print(5 != 3)
print(3 > 5)
print(3 < 5)
print(5 >= 5)
print(4 <= 3)Output
True True False True True False
Comparing different kinds of values
print(5 == 5.0) # same value
print("5" == 5) # text is never equal to a number
print("apple" < "banana") # text is compared alphabetically
print("Zebra" < "apple") # capital letters come first!
print([1, 2] == [1, 2]) # lists compared item by itemOutput
True False True True True
Chained comparisons
Python lets you write a range check the way you would in maths:
age = 25
print(18 <= age < 65) # same as: 18 <= age and age < 65Output
True
3.5Logical operators (combine conditions)
| Operator | Meaning | Example |
|---|---|---|
| and | True only if both are true | age > 18 and has_id |
| or | True if at least one is true | is_weekend or is_holiday |
| not | Flips True to False and back | not True gives False |
age = 20
has_ticket = True
is_vip = False
print(age >= 18 and has_ticket) # both must be True
print(has_ticket or is_vip) # at least one
print(not is_vip) # flips the value
print(age >= 18 and (has_ticket or is_vip)) # brackets make it clearOutput
True True True True
Can this person enter the concert?
age >= 18 True
age >= 18 and has_ticket True
age >= 18 or has_ticket True
The concert needs both, so the rule is the and line: this person can enter. Notice how or is much easier to satisfy.
Every possible combination, in one table:
| a | b | a and b | a or b |
|---|---|---|---|
| True | True | True | True |
| True | False | False | True |
| False | True | False | True |
| False | False | False | False |
3.6Membership operators (is it inside?)
in and not in work on strings, lists, tuples, sets and dictionaries. For a dictionary they check the keys.
print("py" in "python") # inside a string
print(3 in [1, 2, 3]) # inside a list
print("grape" not in ["apple", "banana"])
print(5 in {1, 3, 5}) # inside a set
print("name" in {"name": "Aylin"}) # dict: checks keysOutput
True True True True True
3.7Identity operators
is and is not check whether two names point to the exact same object in memory, not just equal values. Beginners rarely need them, except for checking None.
result = None
print(result is None) # the right way to check for None
a = [1, 2, 3]
b = [1, 2, 3]
c = a
print(a == b) # same values? True
print(a is b) # the very same object? False
print(a is c) # c is just another name for aOutput
True True False True
3.8The same operator on different types
Some operators do different jobs depending on the type of the values:
| Operator | Numbers | Strings | Lists / tuples | Sets |
|---|---|---|---|---|
| + | add | join | join | not allowed (use |) |
| * | multiply | repeat (with an int) | repeat (with an int) | not allowed |
| - | subtract | not allowed | not allowed | difference |
| | & ^ | bit maths (advanced) | not allowed | not allowed | union, intersection, symmetric difference |
| in | not allowed | is the text inside? | is the item inside? | is the item inside? |
Try it yourself
3725 seconds long. Use // and % to print how many hours, minutes and seconds that is.Show a hint
// 3600, then work with what is left over (% 3600).Show the solution
seconds = 3725
hours = seconds // 3600
minutes = seconds % 3600 // 60
rest = seconds % 60
print(hours, minutes, rest)Output
1 2 5
4Setting up your environment (Anaconda and Jupyter)
4.1What is a “programming environment”?
To write Python you need (1) Python itself installed, (2) a place to write and run code, and (3) the libraries for your work. Installing these one by one can be confusing for a beginner. Anaconda packages them together.
- 1
Python itself
the language, installed on your computer
- 2
A place to write and run code
for example Jupyter
- 3
Libraries for your work
ready-made tools such as pandas
Anaconda installs all three in one go.
4.2What is Anaconda?
Anaconda is a free distribution of Python (and R) made for data science. When you install it you get:
Anaconda
Python
Already installed.
Hundreds of libraries
conda
A tool for installing packages and managing separate environments.
Anaconda Navigator
A simple window with buttons to start your tools. It includes launchers for Jupyter Notebook, JupyterLab, Spyder and VS Code, and it can also manage environments and packages.
Jupyter
The notebook tool described below, where you will write and run your code in this course.
4.3What is Jupyter?
Jupyter is a program that runs in your web browser and lets you write code in small blocks called cells, run each block separately, and see the result immediately below it. You can also write notes, headings, and add charts in the same document. This “code + explanation + results” format is why it is the favourite tool of data scientists and students.
My first analysis
Notes like this are written in a Markdown cell.
Markdown cell: headings and notes
Code cell, and its output right below
Empty brackets: not run yet
| Version | What it is |
|---|---|
| Jupyter Notebook | The classic, simple one. Great for beginners. |
| JupyterLab | A more modern workspace with tabs, a file browser, and more features. It uses the same notebook files. |
A Jupyter file has the extension .ipynb (short for “IPython notebook”).
4.4Step-by-step installation
- 1
Download Anaconda.
Go to anaconda.com/download and choose your system (Windows, macOS, or Linux). The site may ask you to sign in with an existing account or create a new Anaconda account before the download. The installer is large, so be patient.
- 2
Run the installer.
Double-click the file and follow the screens. The default settings are fine for most people. On Windows, one training guide advises leaving the “Add Anaconda to my PATH” checkbox unchecked, because adding it can cause conflicts with other software. Installation can take several minutes.
- 3
Open Anaconda Navigator.
Find it in your Start menu (Windows) or Applications folder (Mac).
- 4
Launch Jupyter.
In Navigator, find the Jupyter Notebook (or JupyterLab) box and click Launch. Your browser should open the Jupyter page, where the “New” button lets you create a Python 3 notebook.
- 5
Create your first notebook.
Click New → Python 3. You will see an empty cell. Type the line below (type this and press Shift + Enter). If the text appears under the cell, your setup works.
print("Hello, Data Science!")Output
Hello, Data Science!
To see which Python version you have, run this in a cell:
import sys
print(sys.version)Output
3.12.7 | packaged by Anaconda, Inc. | ... (your version may differ)
4.5Working with cells and shortcuts
| Cell type | What it is for |
|---|---|
| Code cell | Python code you run |
| Markdown cell | Notes, headings, and explanations written in plain text |
Jupyter has two modes. When you click inside a cell and type, you are in edit mode. Press Esc to switch to command mode, where single keys act on the whole cell. That is why many shortcuts start with Esc. Press Enter to go back to typing.
| Keys | What happens |
|---|---|
| Shift+Enter | Run the cell and move to the next one |
| Ctrl+Enter | Run the cell and stay on it |
| EscthenA | Insert a new cell above |
| EscthenB | Insert a new cell below |
| EscthenM | Turn the cell into Markdown |
| EscthenY | Turn the cell back into code |
| EscthenDD | Delete the cell (press D twice) |
4.6The kernel, and why order matters
Behind every notebook runs a kernel, the engine that actually executes your code. It remembers your variables between cells. If something goes wrong or gets stuck, use Kernel → Restart. Remember to shut down the kernel when you finish.
Order matters: if you define x = 5 in cell 3 and use it in cell 1, you must run cell 3 first. When a notebook behaves strangely, restart the kernel and run all cells from the top.
Try it: a notebook with three cells
Run the cells in any order. Watch the numbers in the square brackets and the kernel's memory.
- [ ]:
print(total) - [ ]:
price = 4 - [ ]:
total = price * 3
Kernel memory
Empty
The kernel is running and its memory is empty.
4.7Installing extra libraries
Anaconda includes most libraries, but if you need another one, open Anaconda Prompt (Windows) or the Terminal (Mac/Linux). Both commands work. A good habit is to try conda first, then pip if conda doesn't have it.
conda install package_name
pip install package_name4.8Virtual environments (separate workspaces)
Different projects sometimes need different library versions. A conda environment is a separate, clean workspace for each project so they never conflict. You don't need this on day one, but it is very useful as your projects grow.
school_project
- Python 3.12
- pandas 2.2
old_report
- Python 3.10
- pandas 1.5
conda create -n my_project python
conda activate my_project4.9Other ways to run Python
| Option | What it is | Install needed? |
|---|---|---|
| Miniconda | A smaller version of Anaconda with only the basics. | Yes, small |
| pip + python.org | Installing Python directly. You can then install Jupyter yourself (commands below). | Yes |
| VS Code | A popular code editor with strong Python and notebook support. | Yes |
| Google Colab | A free notebook that runs fully in your browser. Useful for quick starts or if your computer is slow. | No |
pip install notebook
jupyter notebook4.10Common setup problems
| Problem | What to try |
|---|---|
| Navigator won't open or is slow | Wait a minute on first launch; restart the computer |
| Jupyter opens but no browser window appears | Copy the web address shown in the terminal window into your browser |
ModuleNotFoundError | The library isn't installed. Use conda install or pip install |
| Code from an earlier cell “isn't defined” | Run the cells in order, or restart the kernel and run all |
SyntaxError | Check for a missing bracket, quote, or colon |
5Common beginner mistakes
Everyone makes these. Recognizing the error message is half of the fix. The errors below are the real messages Python shows.
Using = when you mean ==
Wrong
age = 18 # this stores 18
Right
age == 18 # this asks: is age 18?
Use one = to store a value and two == to compare.
Forgetting that counting starts at 0
Wrong
fruits = ["apple", "banana", "cherry"] print(fruits[3])
IndexError: list index out of range
Right
fruits = ["apple", "banana", "cherry"] print(fruits[2]) # cherry print(fruits[-1]) # cherry
Mixing text and numbers ("5" + 5 causes an error)
Wrong
print("5" + 5)TypeError: can only concatenate str (not "int") to str
Right
print(int("5") + 5) # 10
print("5" + str(5)) # 55Convert first, then calculate or join.
Misspelling a variable name or using the wrong capital letters
Wrong
age = 20 print(Age)
NameError: name 'Age' is not defined. Did you mean: 'age'?
Right
age = 20 print(age) # 20
Newer Python versions even suggest the name you probably meant.
Forgetting to run an earlier cell in Jupyter
Wrong
print(total) # run before the cell that creates total
NameError: name 'total' is not defined
Right
# run the cell with total = ... first, then: print(total)
Forgetting quotes around text
Wrong
print(Hello)
NameError: name 'Hello' is not defined
Right
print("Hello")print(Hello) is wrong, print("Hello") is right. Without quotes, Python thinks Hello is the name of a variable.
Forgetting to close a bracket or quote
Wrong
print("Hello"SyntaxError: '(' was never closedRight
print("Hello")Every ( needs a ), and every opening quote needs a closing one.
Changing a string or a tuple
Wrong
word = "Python" word[0] = "J"
TypeError: 'str' object does not support item assignment
Right
word = "Python" word = "J" + word[1:] # build a new string
Reading a dictionary key that does not exist
Wrong
student = {"name": "Aylin", "age": 20}
print(student["email"])KeyError: 'email'
Right
student = {"name": "Aylin", "age": 20}
print(student.get("email")) # None6Practice exercises
Try each exercise in a Jupyter cell (or in the lesson notebook) before you open the hint. There is usually more than one correct answer; the solutions show one of them.
Warm-up
One idea at a time.
1.Create variables for your name, age, and favourite number, then print a sentence using an f-string.
Show a hint
Put anfbefore the quotes and the variable names inside{ }.Show one possible solution
Pythonmy_name = "Aylin" my_age = 20 favourite_number = 7 print(f"My name is {my_name}, I am {my_age} and my favourite number is {favourite_number}.")Output
My name is Aylin, I am 20 and my favourite number is 7.
2.Calculate the area of a rectangle with width 8 and height 5, and store it in a variable called
area.Show a hint
Area is width times height. Store the numbers in variables first.Show one possible solution
Pythonwidth = 8 height = 5 area = width * height print(area)Output
40
3.Use
%to check whether the number 47 is even or odd.Show a hint
A number is even whenn % 2 == 0. What is the remainder when you divide 47 by 2?Show one possible solution
Pythonnumber = 47 print(number % 2) # remainder 1 means odd print(number % 2 == 0) # is it even?Output
1 False
4.Make a list of 5 favourite foods, then print the first and last items.
Show a hint
The first item is at position0. The last item is at position-1.Show one possible solution
Pythonfoods = ["pizza", "sushi", "pasta", "salad", "pancakes"] print(foods[0]) print(foods[-1])Output
pizza pancakes
5.Create a dictionary describing a book (title, author, pages) and print the author.
Show a hint
Use curly brackets with key: value pairs, thenbook["author"].Show one possible solution
Pythonbook = {"title": "Animal Farm", "author": "George Orwell", "pages": 112} print(book["author"])Output
George Orwell
6.Write a comparison that checks whether a person aged 17 can vote (age 18 or over) and print the result.
Show a hint
The comparison>=givesTrueorFalse.Show one possible solution
Pythonage = 17 can_vote = age >= 18 print(can_vote)Output
False
Core practice
Combine two or three ideas.
7.Convert
25degrees Celsius to Fahrenheit withF = C * 9 / 5 + 32and print a sentence with both values.Show a hint
Store celsius in a variable, calculate fahrenheit, then use an f-string.Show one possible solution
Pythoncelsius = 25 fahrenheit = celsius * 9 / 5 + 32 print(f"{celsius} C is {fahrenheit} F")Output
25 C is 77.0 F
8.Clean the text
" python FOR data science ": remove the outer spaces, make it Title Case, print it, then print how many words it has.Show a hint
Chain methods:raw.strip().title(). Count words withlen(text.split()).Show one possible solution
Pythonraw = " python FOR data science " clean = raw.strip().title() print(clean) print(len(clean.split()))Output
Python For Data Science 4
9.Turn 200 minutes into hours and minutes, and print it like 3 h 20 min.
Show a hint
Hours:// 60. Minutes left over:% 60.Show one possible solution
Pythontotal_minutes = 200 hours = total_minutes // 60 minutes = total_minutes % 60 print(f"{hours} h {minutes} min")Output
3 h 20 min
10.Start with
shopping = ["milk", "bread"]. Add "eggs" at the end, put "apples" first, remove "bread", then print the list and its length.Show a hint
Useappend,insert(0, ...)andremove.Show one possible solution
Pythonshopping = ["milk", "bread"] shopping.append("eggs") shopping.insert(0, "apples") shopping.remove("bread") print(shopping) print(len(shopping))Output
['apples', 'milk', 'eggs'] 3
11.Store grades in
{"Aylin": 88, "Omar": 92, "Lea": 75}. Add Sam with 81, then print the dictionary, the average grade, and the highest grade.Show a hint
Average:sum(grades.values()) / len(grades). Highest:max(grades.values()).Show one possible solution
Pythongrades = {"Aylin": 88, "Omar": 92, "Lea": 75} grades["Sam"] = 81 average = sum(grades.values()) / len(grades) print(grades) print(average) print(max(grades.values()))Output
{'Aylin': 88, 'Omar': 92, 'Lea': 75, 'Sam': 81} 84.0 9212.Count the different names in
["anna", "ben", "anna", "cara", "ben"]. Then find who visited on both days: Monday{"anna", "ben", "cara"}and Tuesday{"ben", "dan"}.Show a hint
A set removes duplicates;len(set(...))counts them. Both days:&.Show one possible solution
Pythonvisitors = ["anna", "ben", "anna", "cara", "ben"] print(len(set(visitors))) monday = {"anna", "ben", "cara"} tuesday = {"ben", "dan"} print(sorted(monday & tuesday))Output
3 ['ben']
Challenge
Everything from this lesson together.
13.A shop sells 3 items at 4.50 each with 18% tax. Print the subtotal, the tax and the total, each with 2 decimal places.
Show a hint
Subtotal = price * quantity. Tax = subtotal * 0.18. Format with:.2finside an f-string.Show one possible solution
Pythonprice = 4.5 quantity = 3 tax_rate = 0.18 subtotal = price * quantity tax = subtotal * tax_rate total = subtotal + tax print(f"Subtotal: {subtotal:.2f}") print(f"Tax: {tax:.2f}") print(f"Total: {total:.2f}")Output
Subtotal: 13.50 Tax: 2.43 Total: 15.93
14.A year is a leap year if it is divisible by 4 but not by 100, or if it is divisible by 400. Check 2024 and 2026.
Show a hint
Combine%,==,!=,and,orand brackets.Show one possible solution
Pythonyear = 2024 is_leap = (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0) print(is_leap) year = 2026 is_leap = (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0) print(is_leap)Output
True False
15.Build a username from
first = "Aylin",last = "Demir",birth_year = 2005: the first letter of the first name, the last name, all in small letters, then the last two digits of the year.Show a hint
first[0]gives the first letter. Convert the year withstr()and slice[-2:].Show one possible solution
Pythonfirst = "Aylin" last = "Demir" birth_year = 2005 username = (first[0] + last).lower() + str(birth_year)[-2:] print(username)Output
ademir05
7Check yourself
Twelve quick questions. Your answers stay on this page and are not saved.
0 of 12 answered.
8Summary
| Concept | One-line meaning | Example |
|---|---|---|
| Variable | A named box that stores a value | age = 20 |
int / float | Whole numbers / decimal numbers | 7 / 3.14 |
str | Text in quotes | "Hello" |
bool | True or False | True |
None | No value yet | result = None |
list / dict | Ordered group / key-value pairs | [1, 2, 3] / {"a": 1} |
tuple / set | Fixed ordered group / unique values | (1, 2) / {1, 2} |
| Type conversion | Change a value's type | int("5") |
| Arithmetic operators | Do maths | + - * / // % ** |
| Assignment operators | Update a variable | += -= *= /= |
| Comparison operators | Compare values, give True/False | == != > < >= <= |
| Logical operators | Combine conditions | and, or, not |
| Membership / identity | Is it inside? / the same object? | in, is |
| Anaconda | Python plus data science tools in one install | anaconda.com/download |
| Jupyter | Browser tool to run code in cells | Shift + Enter to run |