Asiman Data School

Module 1, topic 1, week 1, Tuesday

Python basics and environment setup

Variables, data types, operators, Anaconda and Jupyter

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 lines and their meaning in plain English
PythonIn plain English
price = 100Store 100 under the name price.
total = price * 3Multiply price by 3 and call the result total.
is_expensive = total > 250Is 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. 1.Create variables, print them, and follow Python's naming rules.
  2. 2.Recognize the data types int, float, str, bool, None, list, tuple, dict and set, and use the main operations of each.
  3. 3.Convert values from one type to another, and know when you must.
  4. 4.Use arithmetic, assignment, comparison, logical, membership and identity operators.
  5. 5.Install Anaconda, open Jupyter, and run code in notebook cells in the right order.
  6. 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.

Python
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

  • age
    20

    type: int

  • height
    1.75

    type: float

  • is_student
    True

    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.”

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).

Python
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.

Python
# 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

  1. 1age = 20
  2. 2age = 21 # the box now holds 21
  3. 3age = age + 1 # take the old value, add 1, store it back

What Python remembers

Nothing stored yet. Press “Run next line”.

Not started
Python
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:

Python
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
Python
first = "tea"
second = "coffee"
first, second = second, first   # swap the two values
print(first, second)

Output

coffee tea

1.5Rules for naming variables

Rules for variable names with examples
RuleWorksDoes not work
Names can contain letters, numbers, and underscores (_).score_2score-2
A name cannot start with a number.score11score
No spaces. Use an underscore instead.student_namestudent name
Python is case-sensitive.Age, age and AGE are three different variables-
Don't use Python's reserved words.class_nameif, for, class, True
Choose meaningful names: price is much better than p. The style lowercase_with_underscores is the Python standard.pricep (works, but unclear)
Python
age = 20
Age = 30
AGE = 40
print(age, Age, AGE)   # three different variables

Output

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:

Python
x = 5
print(type(x))
x = "five"          # the same name now holds text
print(type(x))

Output

<class 'int'>
<class 'str'>

Try it yourself

Create a variable 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
Use print(city, temperature). To increase: temperature = temperature + 2.
Show the solution
Python
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():

Python
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'>
Python
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

Basic Python data types
TypeNameWhat it holdsExample
intIntegerWhole numbers7, -3, 2026
floatFloating-point numberNumbers with a decimal point3.14, -0.5, 2.0
strStringText, always inside quotes"Hello", 'Python'
boolBooleanOnly True or FalseTrue, False
NoneTypeNone“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.

Python
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

Built-in functions for numbers
FunctionWhat it doesExampleResult
abs(x)Distance from zeroabs(-7)7
round(x, n)Round to n decimalsround(3.14159, 2)3.14
min(...), max(...)Smallest, largestmax(4, 9, 1)9
pow(x, y)x to the power ypow(2, 5)32
divmod(a, b)Floor division and remainder togetherdivmod(17, 5)(3, 2)
int(x), float(x)Convertint(7.9)7
Python
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)
Python
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

Python
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
Python
print(2 ** 100)   # Python integers have no size limit

Output

1267650600228229401496703205376

A famous surprise with decimals

Python
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.

Python
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

Escape characters
WriteYou get
\na new line
\ta tab (a wide space)
\"a double quote inside double quotes
\'a single quote inside single quotes
\\one backslash
Python
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 backslash

Output

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.

Python
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 characters

Output

P
n
n
o
6
Python
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])  # reversed

Output

Pyt
thon
Pyth
hon
Pto
nohtyP

Try it: string slicer

Characters of the word with their positions
012345
Python
-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

Python
first = "Data"
second = "Science"
print(first + " " + second)   # join with +
print("ha" * 3)               # repeat with *
print("-" * 20)               # a quick divider line

Output

Data Science
hahaha
--------------------

Changing case

Python
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:

Python
raw = "   Aylin   "
print("[" + raw + "]")
print("[" + raw.strip() + "]")    # both sides
print("[" + raw.lstrip() + "]")   # left side only
print("[" + raw.rstrip() + "]")   # right side only

Output

[   Aylin   ]
[Aylin]
[Aylin   ]
[   Aylin]

Replacing text

Python
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 matches

Output

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

Python
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

Python
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

Python
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.

Python
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 works

Output

Aylin scored 87.456 points
Rounded: 87.5
Two decimals: 87.46
Total students: 1,250
Next year: 21
f-string number formats
Inside the bracesMeaningExample result
{x}the value as it is87.456
{x:.1f}1 decimal place87.5
{x:.2f}2 decimal places87.46
{n:,}thousands separator1,250
{a + b}any expression21

Strings cannot be changed in place

A string is immutable: you cannot change one character. You build a new string instead.

Python
word = "Python"
word[0] = "J"

Error

TypeError: 'str' object does not support item assignment
Python
word = "Python"
new_word = "J" + word[1:]   # build a new string instead
print(new_word)
print(word)                 # the original is unchanged

Output

Jython
Python

String methods at a glance

Common string methods
MethodWhat 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

Start with 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
Use .title(), a slice [:4], len() and .replace(" ", "_").
Show the solution
Python
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.

Python
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:

Python
print(True + True)   # True counts as 1
print(int(False))    # False counts as 0

Output

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.

Values that count as False
Counts as FalseCounts as True
0, 0.042, -1, 0.5
"" (empty string)"hi", " " (a space is a character)
[], (), {}, set() (empty collections)[0] (a list with one item)
None-
Python
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().

Python
result = None
print(result)
print(type(result))
print(result is None)

Output

None
<class 'NoneType'>
True
Python
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:

Python collection types
TypeDescriptionExample
listAn ordered, changeable collection["apple", "banana", "cherry"]
tupleAn ordered collection that cannot be changed(10, 20, 30)
dictPairs of key → value, like a dictionary{"name": "Aylin", "age": 20}
setA collection with no duplicates and no order{1, 2, 3}
Python
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

The list fruits with positive and negative positions
012
"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

102030

Use a tuple for values that belong together and should stay fixed, like a date or a map position.

dictkey → value pairs

"name""Aylin"
"age"20

You look things up by key, not by position: student["name"].

setno duplicates, no order

{1223}

The second 2 is dropped automatically. Handy for finding unique values.

Collections compared
listtupledictset
Brackets[ ]( ){key: value}{ }
Keeps orderYesYesYes (order added)No
Can changeYesNoYesYes
DuplicatesAllowedAllowedKeys must be uniqueRemoved
Get an item bypositionpositionkeycannot (only check with in)

2.8Lists

Creating a list

Python
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.

Python
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 two

Output

apple
mango
['banana', 'cherry']
['apple', 'banana']

Changing an item

Python
fruits = ["apple", "banana", "cherry"]
fruits[1] = "blueberry"   # lists can change
print(fruits)

Output

['apple', 'blueberry', 'cherry']

Adding items

Python
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

Python
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

Python
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.

Python
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

Python
scores = [72, 95, 58, 88]
print(len(scores))
print(min(scores), max(scores))
print(sum(scores))
print(sum(scores) / len(scores))   # the average

Output

4
58 95
313
78.25

Joining and repeating lists

Python
print([1, 2] + [3, 4])   # join two lists
print([0] * 5)           # repeat a list

Output

[1, 2, 3, 4]
[0, 0, 0, 0, 0]

Lists inside lists

Python
grid = [[1, 2, 3],
        [4, 5, 6]]
print(grid[1])      # the second row
print(grid[1][2])   # row 1, position 2

Output

[4, 5, 6]
6

Copying a list (a common trap)

Python
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()

Python
print(list(range(5)))          # 0 up to 5 (not including 5)
print(list(range(2, 10, 2)))   # start 2, stop 10, step 2

Output

[0, 1, 2, 3, 4]
[2, 4, 6, 8]
List operations at a glance
CodeWhat it does
lst[i], lst[a:b]read one item, or a slice
lst[i] = xchange 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, sumsize and quick maths
lst.copy()a real, separate copy

Try it yourself

Start with 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
Use append, insert(0, ...), remove and len.
Show the solution
Python
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.

Python
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'>
Python
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
2

Unpacking: one value per name

Python
point = (3, 4)
x, y = point        # unpacking: one value per name
print(x)
print(y)

Output

3
4

Tuples cannot be changed

Python
colors = ("red", "green", "blue")
colors[0] = "pink"

Error

TypeError: 'tuple' object does not support item assignment
Python
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.

Python
student = {"name": "Aylin", "age": 20, "course": "Data Science"}
print(student)
print(len(student))   # number of key-value pairs

Output

{'name': 'Aylin', 'age': 20, 'course': 'Data Science'}
3

Reading values: [ ] or get()

Python
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 default

Output

Aylin
20
None
not given

Square brackets stop with an error when the key is missing. get() gives None (or your default) instead:

Python
student = {"name": "Aylin", "age": 20}
print(student["email"])

Error

KeyError: 'email'

Adding and changing

Python
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

Python
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

Python
student = {"name": "Aylin", "age": 20}
print(student.keys())
print(student.values())
print(student.items())
print(list(student.keys()))   # as a normal list

Output

dict_keys(['name', 'age'])
dict_values(['Aylin', 20])
dict_items([('name', 'Aylin'), ('age', 20)])
['name', 'age']
Python
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)

Python
course = {
    "title": "Python basics",
    "topics": ["variables", "data types", "operators"],
}
print(course["topics"])
print(course["topics"][1])

Output

['variables', 'data types', 'operators']
data types
Dictionary operations at a glance
CodeWhat it does
d[key]read a value (error if the key is missing)
d.get(key, default)read safely
d[key] = valueadd 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

Create 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
Adding and changing both use phone[key] = value.
Show the solution
Python
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}
unknown

2.11Sets

A set keeps each value only once and has no order. It is perfect for removing duplicates and for comparing groups.

Python
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'>
Python
grades = [90, 85, 90, 70, 85]
unique = set(grades)
print(len(unique))      # how many different grades
print(sorted(unique))   # as a sorted list

Output

3
[70, 85, 90]

Adding and removing

Python
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}
Python
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

Python
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 them

Output

{1, 2, 3, 4, 5, 6}
{3, 4}
{1, 2}
{5, 6}
{1, 2, 5, 6}
Python
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}
True

Try it yourself

Students who came on Monday: {"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
Both days is &; at least once is |. Wrap the result in sorted() for a fixed order.
Show the solution
Python
monday = {"Ali", "Ben", "Cara"}
tuesday = {"Ben", "Cara", "Dana"}
print(sorted(monday & tuesday))   # came both days
print(sorted(monday | tuesday))   # came at least once

Output

['Ben', 'Cara']
['Ali', 'Ben', 'Cara', 'Dana']

2.12Converting between types (type casting)

Sometimes you need to change a value from one type to another:

Converting between types
CodeResultWhat happened
int("5")5text → whole number
float(3)3.0whole number → decimal
str(10)"10"number → text
int(3.9)3cuts 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")ValueErrorint() cannot read a decimal from text
Python
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 -> float

Output

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.

Python
print("5" + "5")             # text: glued together
print(int("5") + int("5"))   # numbers: added
print("5" * 3)               # text repeated

Output

55
10
555
Python
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 -> dict

Output

['a', 'b', 'c']
(1, 2, 3)
{1, 2}
[4, 5]
{'a': 1, 'b': 2}

When conversion fails

Python
print(int("3.5"))

Error

ValueError: invalid literal for int() with base 10: '3.5'
Python
print(int(float("3.5")))   # text -> float -> int

Output

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.)

Python
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)

Arithmetic operators
OperatorMeaningExampleResult
+Add7 + 29
-Subtract7 - 25
*Multiply7 * 214
/Divide (always gives a float)7 / 23.5
//Floor division (drops the decimals)7 // 23
%Modulus (the remainder)7 % 21
**Power2 ** 38
Python
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)   # power

Output

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:

Python
n = 47
print(n % 2)        # remainder after dividing by 2
print(n % 2 == 0)   # True would mean "even"

Output

1
False
Python
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.

  1. 2 + 3 * 4multiplication first
  2. 2 + 12then addition
  3. 14
  1. (2 + 3) * 4brackets first
  2. 5 * 4then multiplication
  3. 20
Python
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
Python operator precedence, highest first
OrderOperators
1 (first)( )
2**
3-x (a minus sign in front)
4* / // %
5+ -
6== != < > <= >= in not in is is not
7not
8and
9 (last)or

3.3Assignment operators (store and update)

These are shortcuts for updating a variable:

Assignment operators
OperatorSame asExample (x starts at 10)
=storex = 10
+=x = x + nx += 5 gives 15
-=x = x - nx -= 3 gives 7
*=x = x * nx *= 2 gives 20
/=x = x / nx /= 4 gives 2.5
//=x = x // nx //= 3 gives 3
%=x = x % nx %= 3 gives 1
**=x = x ** nx **= 2 gives 100

Updating x with assignment shortcuts

  1. 1x = 10
  2. 2x += 5 # same as x = x + 5
  3. 3x -= 3 # same as x = x - 3
  4. 4x *= 2 # same as x = x * 2
  5. 5x /= 4 # same as x = x / 4

What Python remembers

Nothing stored yet. Press “Run next line”.

Not started
Python
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
Python
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)

Comparison operators
OperatorMeaningExampleResult
==Equal to5 == 5True
!=Not equal to5 != 3True
>Greater than3 > 5False
<Less than3 < 5True
>=Greater than or equal5 >= 5True
<=Less than or equal4 <= 3False

age = 18

Stores. Puts 18 into the box called age.

age == 18

Asks. Is age 18? The answer is True or False.

Python
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

Python
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 item

Output

True
False
True
True
True

Chained comparisons

Python lets you write a range check the way you would in maths:

Python
age = 25
print(18 <= age < 65)   # same as: 18 <= age and age < 65

Output

True

3.5Logical operators (combine conditions)

Logical operators
OperatorMeaningExample
andTrue only if both are trueage > 18 and has_id
orTrue if at least one is trueis_weekend or is_holiday
notFlips True to False and backnot True gives False
Python
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 clear

Output

True
True
True
True

Can this person enter the concert?

age =20

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:

Truth table for and and or
aba and ba or b
TrueTrueTrueTrue
TrueFalseFalseTrue
FalseTrueFalseTrue
FalseFalseFalseFalse

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.

Python
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 keys

Output

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.

Python
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 a

Output

True
True
False
True

3.8The same operator on different types

Some operators do different jobs depending on the type of the values:

What operators do to each type
OperatorNumbersStringsLists / tuplesSets
+addjoinjoinnot allowed (use |)
*multiplyrepeat (with an int)repeat (with an int)not allowed
-subtractnot allowednot alloweddifference
| & ^bit maths (advanced)not allowednot allowedunion, intersection, symmetric difference
innot allowedis the text inside?is the item inside?is the item inside?

Try it yourself

A video is 3725 seconds long. Use // and % to print how many hours, minutes and seconds that is.
Show a hint
One hour is 3600 seconds. Take the hours with // 3600, then work with what is left over (% 3600).
Show the solution
Python
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. 1

    Python itself

    the language, installed on your computer

  2. 2

    A place to write and run code

    for example Jupyter

  3. 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

pandasNumPymatplotlibscikit-learn

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

[1]:print("Hello, Data Science!")
Hello, Data Science!

Code cell, and its output right below

[ ]:your next cell

Empty brackets: not run yet

A notebook is a list of cells. The number in the brackets shows the order in which cells were run.
The two versions of Jupyter
VersionWhat it is
Jupyter NotebookThe classic, simple one. Great for beginners.
JupyterLabA 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. 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. 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. 3

    Open Anaconda Navigator.

    Find it in your Start menu (Windows) or Applications folder (Mac).

  4. 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. 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.

Python
print("Hello, Data Science!")

Output

Hello, Data Science!

To see which Python version you have, run this in a cell:

Python
import sys
print(sys.version)

Output

3.12.7 | packaged by Anaconda, Inc. | ... (your version may differ)

4.5Working with cells and shortcuts

Jupyter cell types
Cell typeWhat it is for
Code cellPython code you run
Markdown cellNotes, 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.

Useful Jupyter keyboard shortcuts
KeysWhat happens
Shift+EnterRun the cell and move to the next one
Ctrl+EnterRun the cell and stay on it
EscthenAInsert a new cell above
EscthenBInsert a new cell below
EscthenMTurn the cell into Markdown
EscthenYTurn the cell back into code
EscthenDDDelete 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.

  1. [ ]:print(total)
  2. [ ]:price = 4
  3. [ ]: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.

Terminal
conda install package_name
pip install package_name

4.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
Two environments on one computer, each with its own versions. Version numbers are examples.
Terminal
conda create -n my_project python
conda activate my_project

4.9Other ways to run Python

Other ways to run Python
OptionWhat it isInstall needed?
MinicondaA smaller version of Anaconda with only the basics.Yes, small
pip + python.orgInstalling Python directly. You can then install Jupyter yourself (commands below).Yes
VS CodeA popular code editor with strong Python and notebook support.Yes
Google ColabA free notebook that runs fully in your browser. Useful for quick starts or if your computer is slow.No
Terminal
pip install notebook
jupyter notebook

4.10Common setup problems

Common setup problems and what to try
ProblemWhat to try
Navigator won't open or is slowWait a minute on first launch; restart the computer
Jupyter opens but no browser window appearsCopy the web address shown in the terminal window into your browser
ModuleNotFoundErrorThe 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
SyntaxErrorCheck 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))    # 55

Convert 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 closed

Right

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"))   # None

6Practice 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. 1.Create variables for your name, age, and favourite number, then print a sentence using an f-string.

    Show a hint
    Put an f before the quotes and the variable names inside { }.
    Show one possible solution
    Python
    my_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. 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
    Python
    width = 8
    height = 5
    area = width * height
    print(area)

    Output

    40
  3. 3.Use % to check whether the number 47 is even or odd.

    Show a hint
    A number is even when n % 2 == 0. What is the remainder when you divide 47 by 2?
    Show one possible solution
    Python
    number = 47
    print(number % 2)        # remainder 1 means odd
    print(number % 2 == 0)   # is it even?

    Output

    1
    False
  4. 4.Make a list of 5 favourite foods, then print the first and last items.

    Show a hint
    The first item is at position 0. The last item is at position -1.
    Show one possible solution
    Python
    foods = ["pizza", "sushi", "pasta", "salad", "pancakes"]
    print(foods[0])
    print(foods[-1])

    Output

    pizza
    pancakes
  5. 5.Create a dictionary describing a book (title, author, pages) and print the author.

    Show a hint
    Use curly brackets with key: value pairs, then book["author"].
    Show one possible solution
    Python
    book = {"title": "Animal Farm", "author": "George Orwell", "pages": 112}
    print(book["author"])

    Output

    George Orwell
  6. 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 >= gives True or False.
    Show one possible solution
    Python
    age = 17
    can_vote = age >= 18
    print(can_vote)

    Output

    False

Core practice

Combine two or three ideas.

  1. 7.Convert 25 degrees Celsius to Fahrenheit with F = C * 9 / 5 + 32 and 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
    Python
    celsius = 25
    fahrenheit = celsius * 9 / 5 + 32
    print(f"{celsius} C is {fahrenheit} F")

    Output

    25 C is 77.0 F
  2. 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 with len(text.split()).
    Show one possible solution
    Python
    raw = "  python FOR data science  "
    clean = raw.strip().title()
    print(clean)
    print(len(clean.split()))

    Output

    Python For Data Science
    4
  3. 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
    Python
    total_minutes = 200
    hours = total_minutes // 60
    minutes = total_minutes % 60
    print(f"{hours} h {minutes} min")

    Output

    3 h 20 min
  4. 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
    Use append, insert(0, ...) and remove.
    Show one possible solution
    Python
    shopping = ["milk", "bread"]
    shopping.append("eggs")
    shopping.insert(0, "apples")
    shopping.remove("bread")
    print(shopping)
    print(len(shopping))

    Output

    ['apples', 'milk', 'eggs']
    3
  5. 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
    Python
    grades = {"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
    92
  6. 12.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
    Python
    visitors = ["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.

  1. 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 :.2f inside an f-string.
    Show one possible solution
    Python
    price = 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
  2. 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, or and brackets.
    Show one possible solution
    Python
    year = 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
  3. 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 with str() and slice [-2:].
    Show one possible solution
    Python
    first = "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.

Question 1

1.What does this print?

print(7 // 2)

Question 2

2.What does this print?

print(10 / 2)

Question 3

3.What type is this value?

type("20")

Question 4

4.What does this print?

print("5" + "5")

Question 5

5.What does this print?

word = "Python"
print(word[-2])

Question 6

6.What does this print?

print(len("Data Science"))

Question 7

7.What does this print?

fruits = ["apple", "banana", "cherry"]
print(fruits[1])

Question 8

8.What does this print?

student = {"name": "Aylin"}
print("Aylin" in student)

Question 9

9.What does this print?

print({1, 2, 2, 3})

Question 10

10.What does this print?

print(bool(""))

Question 11

11.Which line stores 18 in age?

Question 12

12.In Jupyter, which keys run a cell and move to the next one?

0 of 12 answered.

8Summary

Quick summary of Topic 1
ConceptOne-line meaningExample
VariableA named box that stores a valueage = 20
int / floatWhole numbers / decimal numbers7 / 3.14
strText in quotes"Hello"
boolTrue or FalseTrue
NoneNo value yetresult = None
list / dictOrdered group / key-value pairs[1, 2, 3] / {"a": 1}
tuple / setFixed ordered group / unique values(1, 2) / {1, 2}
Type conversionChange a value's typeint("5")
Arithmetic operatorsDo maths+ - * / // % **
Assignment operatorsUpdate a variable+= -= *= /=
Comparison operatorsCompare values, give True/False== != > < >= <=
Logical operatorsCombine conditionsand, or, not
Membership / identityIs it inside? / the same object?in, is
AnacondaPython plus data science tools in one installanaconda.com/download
JupyterBrowser tool to run code in cellsShift + Enter to run