Lecture 2: Introduction to Python Programming, Part 1#

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.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
10 - 20
10 * 20
10 / 20
((10 + 20) * (5 - 2)) / 3.5

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

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 floats to a specific number of decimal places.

round(3.6789, 2)

Function terminology#

The expression round(3.6789, 2) is called a function call.

  • round is the name of the function

  • 3.6789 and 2 are the inputs/arguments of the function

  • The value 3.68 is the output/return value of the function

Here are two other examples of Python functions:

abs(-4.3)
type(-4.3)

Comparisons and the bool data type#

We can compare numbers using the following comparison operators:

Operation

Description

a == b

Are a and b equal?

a != b

Are a and b not equal?

a > b

Is a greater than b?

a < b

Is a less than b?

a >= b

Is a greater than or equal to b?

a <= b

Is a less than or equal to b?

3 == 3
10 * 2 <= 3 * 6

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

a and b produces whether both a and b are True:

True and False

a or b evaluates to whether at least one of a and b are True:

True or False
(5 < 10) and (3 * 5 < 2 * 7)

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!'
"Dark chocolate is the best."

We can check whether two strings are equal:

"chocolate" == "chocolate"

This comparison is case-sensitive:

"Hello" == "hello"

We can use a new operator, in, to check whether one string is contained inside another:

"cat" in "education"

We can concatenate strings together using the + operator:

"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]

Finally, we can use the len function to compute the number of characters of a string:

len("Hello World!")

Exercise 2#

Write a Python expression to compute whether the name "Michael Moon" is longer than "Chunjiang Li".

(The word ā€œwhetherā€ signals that the output should be a boolean, i.e., either True or False.)

# Write your code in the space below

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 = "Karen"

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 "Karen".

We can then access the value of this variable:

name
name + " likes chocolate."
len(name)

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)

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)

Python follows two conventions for writing variable names:

  • make all letters lowercase (so amount, not Amount or AMOUNT)

  • separate words with underscores so (tax_rate, not tax rate or taxrate)

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

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)

f-strings#

Suppose have have a student’s name and a course’ code, and want to compute a welcome message like "Hello Karen, you are currently in GGR274!"

name = "Karen"
course = "GGR274"

welcome_message = "Hello " + name + ", you are currently in " + course + "!"
welcome_message

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

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 = "Karen"

name.upper()

Here are some common string methods you may find useful:

String method

Description

str.upper()

Convert the string to uppercase.

str.lower()

Convert the string to lowercase.

str.count(other)

Return the number of times other appears in the string.

str.replace(old, new)

Replace all occurrences of old with new in the string.

str.split()

Return a list of the words in the string, separating by spaces.

my_string = "Karen likes chocolate."

my_string.replace("Karen", "Michael")

str.split and the Python list data type#

my_string = "Karen likes chocolate."

my_string.split()

What exactly is ['Karen', 'likes', 'chocolate']?

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)

Okay! ['Karen', 'likes', 'chocolate'] is a list.

In Python, list are used to store multiple values in a sequence (i.e., with a defined order).

List examples#

Python lists are very versatile, and can be used to store different kinds of values. We write lists by using square brackets: [...].

# A list of strings:
["Karen", "likes", "chocolate"]
# A list of ints
[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]
[1, 2, 3] == [3, 2, 1]
False

We can compute the length of a list using the len function:

len(["Karen", "likes", "chocolate"])

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:

  1. Calculate the length of the list (i.e., number of numbers in the list). Call this number my_len.

  2. Calculate the sum of the numbers in the list. Call this number my_sum.

  3. Calculate the average of the numbers in the list. Call this number my_avg.

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

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 = "Karen"

  • Run Python code and display results in a Jupyter notebook (like this one!)