Lecture 2: Introduction to Python Programming, Part 1#
Logistics check#
At this point it is time:
To know how to open class notebook in JupyterHub
Understand how to save Lab or Homework notebook to your computer
Understand how to upload Lab or Homework to Markus
Understand how to run tests on Markus
If you are not there yet, please make sure you get help during the lab/office hours or ask on Piazza
Context: Some things to remember#
Computer programming languages are actually for people, not for computers :)
To some extent, learning a new programming language is quite like learning a new (written) human language, but ā¦ easier
Vocabulary is much, much smaller
Syntax/Grammar are much simpler
The main limitation is that the computer (of pre-GPT era) is much more limited in understanding and thus more strict
The real barrier is understanding what you want to do and explaining that in a clear non self-contradictory way
Part of that is being able to explain the data and the task you are dealing with in a specific way so that you can use rich instruments provided by Python environment.
Learning objectives#
In this lecture, you will learn to:
Identify and describe values of different types in Python code
Perform simple computations on these values
Store values and the results of computations in variables
Run Python code and display results in a Jupyter notebook (like this one!)
Representing Data in Python: numbers#
Python can represent both integer and fractional numbers by writing them the same way you would in text:
3
3
-3.5
-3.5
int
and float
#
Python defines two data types to categorize numbers: int
and float
.
An int
represents an integer like 3
or -4
.
A float
, short for floating point number, represents a fractional number like 3.5
or -4.5
.
Arithmetic in Python#
We can combine numbers using basic arithmetic operations like +
, -
, *
, and /
:
10 + 20
30
10 - 20
-10
10 * 20
200
10 / 20
0.5
((10 + 20) * (5 - 2)) / 3.5
25.714285714285715
Exercise 1#
Suppose you go out to eat at a restaurant, and your before-tax total is $15.99.
Assuming there is a 13% tax and 15% tip (on the before-tax price), use Python to calculate the total amount that you pay.
# Write your Python code in the space below
Solution (only look at this after attempting the exercise!)
15.99 * (1 + 0.13 + 0.15)
20.4672
Rounding and the round
function#
Python provides functions, which are named blocks of code that perform a specific computation.
The round
function lets us round float
s to a specific number of decimal places.
round(3.6789, 2)
3.68
Function terminology#
The expression round(3.6789, 2)
is called a function call.
round
is the name of the function3.6789
and2
are the inputs/arguments of the functionThe value
3.68
is the output/return value of the function
Here are two other examples of Python functions:
abs(-4.3)
4.3
type(-4.3)
float
Comparisons and the bool
data type#
We can compare numbers using the following comparison operators:
Operation |
Description |
---|---|
|
Are |
|
Are |
|
Is |
|
Is |
|
Is |
|
Is |
3 == 3
True
10 * 2 <= 3 * 6
False
Python displays True
and False
as a result of a comparison.
True
and False
are the two values of the bool
data type, short for boolean.
Boolean values represent answers to Yes/No questions like:
Is this person a Canadian citizen?
Is this movie less than 2 hours long?
Is every student in this lecture paying attention right now?
Manipulating booleans#
We can perform three operations on booleans: not
, and
, or
.
not b
negates the value of b
, so True
becomes False
and vice versa.
not True
False
a and b
produces whether both a
and b
are True
:
True and False
False
a or b
evaluates to whether at least one of a
and b
are True
:
True or False
True
(5 < 10) and (3 * 5 < 2 * 7)
False
Text data and the str
data type#
str
, short for string, is a type of data for representing text.
A string is a sequence of characters, where each character could be:
English letters (a, b, c)
numeric digits (0, 1, 2, etc.)
letters and glyphs from languages other than English (e.g., Ł, Ī¾, ä½ )
punctuation marks and symbols (such as the period (.) and at symbol @)
spaces
emojis (e.g., š, š§, š«)
In Python, we write strings by writing text surrounded by either single-quotes or double-quotes.
'Hello, world!'
'Hello, world!'
"You are cool"
'You are cool'
"You are 'cool'"
"You are 'cool'"
We can check whether two strings are equal:
"cool" == 'cool'
True
This comparison is case-sensitive:
"cool" == "COOL"
False
We can use a new operator, in
, to check whether one string is contained inside another:
"cat" in "education"
True
We can concatenate strings together using the +
operator:
"Hello" + "World!"
'HelloWorld!'
"Hello " + "World!"
'Hello World!'
We can access a specific character in the string by its position (or āindexā) using square bracket notation.
Note: in Python, positions/indexes start at 0, not 1!
"Hello World!"[0]
'H'
"Hello World!"[0:5]
'Hello'
Finally, we can use the len
function to compute the number of characters of a string:
len("Hello World!")
12
Exercise 2#
Write a Python expression to compute whether the word "hippopotamus"
is longer than "elephant"
.
(The word āwhetherā signals that the output should be a boolean, i.e., either True
or False
.)
# Write your code in the space below
Solution (only look at this after attempting the exercise!)
len("hippopotamus") > len("elephant")
True
How about "hippopotamus"
and "hippocampus"
?
# Write your code in the space below
Summary of this part (use that at home to revise):#
We now know some Python data types, allowing us to represent our data:
Numbers:
int
andfloat
Logical (Boolean):
bool
Strings:
str
We know that data helps us to explain to Python what we can do with data
Operation |
Applied to type ā¦ |
Results is of type ā¦ |
Example |
---|---|---|---|
|
|
|
ā¦. |
|
|
|
|
|
|
||
ā¦ |
Continue at home! Can some functions or operators be aplied to other types?
Variables#
As our code gets more complex, weāll use variables to keep track of our values.
A variable is a piece of code that refers to a value.
We create variables using code called an assignment statement, which looks like:
<variable> = <expression>
name = "Ilya"
When we evaluated the previous code cell, nothing was displayed!
But the code did execute: what it did was tell Python to create a variable called name
and make it refer to the value "Ilya"
.
We can then access the value of this variable:
name
'Ilya'
name + " is not an early bird"
'Ilya is not an early bird'
len(name)
4
sad_truth = name + " is not an early bird"
Jupyter notebooks let us write multiple statements in a single code cell. This lets us write one block of code where we define variables and use them in the same cell.
amount = 15.99
tax_rate = 0.13
tip_rate = 0.15
total_amount = amount * (1 + tax_rate + tip_rate)
round(total_amount)
20
Naming variables#
Even though Python lets us name variables whatever we want, it is important to pick meaningful variable names!
If you donāt, you might end up reading code that looks like this:
lol = 15.99
lmao = 0.13
x = 0.15
wtf = lol * (1 + lmao + x)
round(wtf)
20
Python follows two conventions for writing variable names:
make all letters lowercase (so
amount
, notAmount
orAMOUNT
)separate words with underscores so (
tax_rate
, nottax rate
ortaxrate
)
The print
function#
Normally when we execute a notebook cell with multiple expressions/statements, only the value of the last one is displayed.
3 + 4
5 + 6
7 + 8
15
We can use the built-in Python function print
to display multiple values in the cell output.
print(3 + 4)
print(5 + 6)
print(7 + 8)
7
11
15
f-strings#
Suppose have have a studentās name and a courseā code, and want to compute a welcome message like "Hello Ilya, you are currently in GGR274!"
name = "Your Name"
course = "GGR274"
welcome_message = "Hello " + name + ", you are currently in " + course + "!"
welcome_message
'Hello Your Name, you are currently in GGR274!'
This is a bit ugly, so Python gives us a way of writing a string with single-/double-quotes, but marking certain parts as Python expressions that should be evaluated to build the string.
These are called f-strings (short for āformatted string literalā).
welcome_message2 = f"Hello {name}, you are currently in {course}!"
welcome_message2
'Hello Your Name, you are currently in GGR274!'
String Methods#
Strings are the most complex form of data weāve studied so far, and there are a lot more operations we can perform on them beyond ==
, in
, and len
.
Most of these operations are implemented as string methods.
A method is a function that is defined as part of a data type.
We refer to methods using ādot notationā: <type>.<method name>
.
For example, str.upper
is a string method that converts a string to ALL CAPS.
We can call the method by putting a string value to the left of the dot in Python code:
name = "yourname"
name.upper()
'YOURNAME'
Here are some common string methods you may find useful:
String method |
Description |
---|---|
|
Convert the string to uppercase. |
|
Convert the string to lowercase. |
|
Return the number of times |
|
Replace all occurrences of |
|
Return a list of the words in the string, separating by spaces. |
my_string = "I am cool"
my_string.replace("I am", "You are")
'You are cool'
Donāt forget to add examples to other methods!
str.split
and the Python list
data type#
my_string = "I am cool"
my_string.split()
['I', 'am', 'cool']
What exactly is ['I', 'am', 'cool']
?
It contains strings, but is not one big string itself.
Letās use the type()
function to see what kind of value it is according to Python:
mystery_value = my_string.split()
type(mystery_value)
list
Okay! ['I', 'am', 'cool']
is a list
.
In Python, list
are used to store multiple values in a sequence (i.e., with a defined order).
List examples#
Python list
s are very versatile, and can be used to store different kinds of values. We write lists by using square brackets: [...]
.
# A list of strings:
['I', 'am', 'cool']
['I', 'am', 'cool']
# A list of ints
[3, 5, 10000]
[3, 5, 10000]
# An *empty* list
[]
[]
List operations#
Lists support many of the same operations as strings, since both are āsequencesā.
Lists can be compared using ==
. Note: order matters!
[1, 2, 3] == [1, 2, 3]
True
[1, 2, 3] == [3, 2, 1]
False
We can compute the length of a list using the len
function:
len(['I', 'am', 'cool'])
3
We can calculate the sum of a list of numbers using the sum
function:
sum([10, 20, 30])
60
Exercise 3: Putting it all together#
Given the list of numbers defined in the variable my_numbers
, do the following:
Calculate the length of the list (i.e., number of numbers in the list). Call this number
my_len
.Calculate the sum of the numbers in the list. Call this number
my_sum
.Calculate the average of the numbers in the list. Call this number
my_avg
.Print out a message of the form
"The average of my_numbers is {my_avg}"
, where{my_avg}
is replaced by the average of the numbers.
my_numbers = [1, -4.5, 333, 274, -1000, 0]
# Write your code in the space below
Solution (only look at this cell after attempting the above exercise!)
my_numbers = [1, -4.5, 333, 274, -1000, 0]
# Write your code in the space below
my_len = len(my_numbers)
my_sum = sum(my_numbers)
my_avg = my_sum / my_len
print(f"The average of my_numbers is {my_avg}")
The average of my_numbers is -0.015132408575031526
Exercise 4:#
Experiment more!
Write down how much do you like the music of the following artists (letās use -5 to +5 scale, -5 absolutely canāt stand, 0 - idk/neutral, +5 on repeat, actually listening right now)
Drake, Tame Impala, Billie Eilish, The Weeknd, Taylor Swift
Write down the same for one of your friends or family members (or make up an imaginary friend)
Think how to answer based on this data:
How enthusiastic about music you and your friend are?
How would you approach comparing music tastes between two people?
Write down your idea first and then you can try to put it into code!
Learning objectives#
In this lecture, you learned to:
Identify and describe values of different types in Python code
int
,float
,bool
,str
,list
Perform simple computations on these values
arithmetic, comparisons, functions (e.g.
round
,abs
), string methods (e.g.str.upper
,str.split
)
Store values and the results of computations in variables
e.g.
name = "Ilya"
Run Python code and display results in a Jupyter notebook (like this one!)