Lesson 1

Overview

  1. Self-introductions

  2. Conda

  • Environments
  1. Importing packages

  2. Variables

  • Assignment (using =)
  • Naming
  • Types (str, int, float, bool, lists/tuples/sets, dicts)
  • For ints/floats: operations
  • Lists/tuples/sets and dicts
    • For lists/tuples: subsets, len(), sum(), max(), min(), etc.
  • For strings: subsets, addition, and f-strings
  1. Introduction to if statements, loops, and functions
  • Concepts
  • Shared syntax
    • Colons
    • Indentation
  1. If statements
  • Comparisons
  • and and or
  1. Loops
  • For loops
  • While loops
  • Breaks
  • Continue
  1. Functions
  • Arguments
  • Returns
  • Comments
    • Docstrings
  1. Printing text

1. Self-introductions

2. Conda

Does lots of things, we’re using it for package management

Packages are how people share their code with others

2.1 Environments

Allows you to keep packages organized - see here

  • To create: conda create --name pycourse (you can replace pycourse with any custom name)
  • To activate: conda activate pycourse
  • To install pip: conda install pip
  • To install package: pip install packagename (replace packagename with the name of the package you want to install)
    • For this lesson, please install: jupyterlab and/or notebook to be able to open Jupyter Notebooks (like this) (see here for more information)
  • Link to environment features: Conda environments

2.2 Alternative to Jupyter

#%%
import random
random.random()

3. Importing packages

Type import packagename

import random
print(random.random())
0.307089595181008
import random as rand
print(rand.random())
0.5923790629209741

4. Variables

Why - you need to keep track of what’s what

4.1 Assignment

Assign a value to a name using = (this is not equivalent to mathematical equality, check that using ==)

x = 10
print(x)
10

4.2 Naming

Choose names carefully

x = 10
distance = 10

4.3 Types

str, int, float, bool, lists/tuples/sets, dicts

course_name_v1 = 'Python Course, Summer 2024'
course_name_v2 = "Python Course, Summer 2024"
course_name_v3 = \
'''
Python Course, Summer 2024
'''
course_year = 2024
lecture_1_frac_complete = 1/5 # Or 0.2
lecture_1_complete = False # Or True
lectures = [1, 2, 3, 4, 5, 6, 7, 8] # Mutable
lecture_v2 = (1, 2, 3, 4, 5, 6, 7, 8) # Immutable
lectures_v3 = {1, 2, 3, 4, 5, 6, 7, 8, 8}
lectures_occurred = {1: 'True', 2: 'False', 3: 'False', 4: 'False', 5: 'False', 6: 'False', 7: 'False', 8: 'False'}

4.4 For ints/floats: operations

  • Addition: +
  • Subtraction: -
  • Multiplication: *
  • Division: /
  • Exponentiation: **
  • In-place: +=, -=, *=, /=, **=
a = 5
b = 2.0
print(a + b)
7.0
a = a + b
print(a)
7.0
a += b
print(a)
9.0
a = 5
a *= b
print(a)
10.0
a = 5
a **= b
print(a)
25.0

4.5 Lists/tuples/sets and dicts

Lists are mutable (they can be changed) - Access an element using list[index] (indexing starts at 0)

Tuples are immutable (they cannot be changed) - Access an element using tuple[index] (indexing starts at 0)

Sets don’t have an order

Dicts work like a dictionary (a term called a ‘key’ will be linked to an associated variable called a ‘value’) - Access a value using dict[key] - Treats ints and floats as equivalent (so 1 and 1.0 are the same key)

print(lectures)
lectures[0] = 0
print(lectures)
[1, 2, 3, 4, 5, 6, 7, 8]
[0, 2, 3, 4, 5, 6, 7, 8]
print(lecture_v2)
lecture_v2[0] = 0
(1, 2, 3, 4, 5, 6, 7, 8)
TypeError: 'tuple' object does not support item assignment
print(lectures_v3)
lectures_v3[0] = 0
{1, 2, 3, 4, 5, 6, 7, 8}
TypeError: 'set' object does not support item assignment
print(lectures_occurred)
lectures_occurred[0] = False
print(lectures_occurred)
lectures_occurred['word'] = 'definition'
print(lectures_occurred)
{1: 'True', 2: 'False', 3: 'False', 4: 'False', 5: 'False', 6: 'False', 7: 'False', 8: 'False'}
{1: 'True', 2: 'False', 3: 'False', 4: 'False', 5: 'False', 6: 'False', 7: 'False', 8: 'False', 0: False}
{1: 'True', 2: 'False', 3: 'False', 4: 'False', 5: 'False', 6: 'False', 7: 'False', 8: 'False', 0: False, 'word': 'definition'}

4.5.1 For lists/tuples: subsets, len(), sum(), max(), min(), etc.

Access a subset of a list/tuple using list[a: b]/tuple[a: b], which gives you the elements starting and index a and ending at index b-1 (remember that indexing starts at 0)

print(lectures)
print('Length of list:', len(lectures))
print('Subset of list:', lectures[2: 4])
print('Last element of list:', lectures[len(lectures)-1])
print('Alternative last element of list:', lectures[-1])
print('Max of tuple:', max(lecture_v2))
print('Min of tuple:', min(lecture_v2))
[0, 2, 3, 4, 5, 6, 7, 8]
Length of list: 8
Subset of list: [3, 4]
Last element of list: 8
Alternative last element of list: 8
Max of tuple: 8
Min of tuple: 1

4.6 For strings: subsets, addition, and f-strings

Access substrings as if the string is a list

a = 'hello'
a[3: 5]
'lo'
a[0]
'h'
a[2:]
'llo'
a[-3:]
'llo'

Warning: indexing outside of strings doesn’t raise an error

a[2:100]
'llo'

Strings can be combined using +

a = 'hello'
b = 'goodbye'
a + b
'hellogoodbye'

Variables can easily be put into strings using f-strings

a = 5
b = 6
f'a is {a} and b is {b}'
'a is 5 and b is 6'

5. Introduction to if statements, loops, and functions

For this section, if must is capitalized (as MUST), it means the code won’t run if you don’t do this. It is not a recommendation but rather a requirement.

5.1 Concepts

  • If statements: if you want a task to occur under certain conditions
  • Loops: if you want to repeat a task consecutively for the same context
  • Functions: if you want to repeat a task, potentially non-consecutively, for potentially different contexts

5.2 Shared syntax

5.2.1 Colons

The line of code where if statements, loops, and functions are initiated MUST end with a colon

5.2.2 Indentation

The code included inside of if statements, loops, and functions MUST be properly indented (4 spaces)

Nested if statements, loops, and functions MUST have nested indentation

6. If statements

If you want a task to occur under certain conditions

6.1 Comparisons

  • == for equality
  • != for inequality
  • > or < for strict inequality
  • >= or <= for weak inequality
  • in for list membership
  • is for variable reference ids and None
x
10
if x == 8:
    print('x is 8')
elif x == 9:
    print('x is 9')
else:
    print('x is neither 8 nor 9')
x is neither 8 nor 9

If a variable is already a boolean, it can directly be used as a comparison - conciseness is preferred

a = 5
x = (a == 5)
if x: # Preferred
    print('x is True since a is 5')
else:
    print('x is False since a is not 5')
if x == True: # Works, but not preferred
    print('x is True since a is 5')
else:
    print('x is False since a is not 5')
x is True since a is 5
x is True since a is 5
list1 = [1, 2, 3]
list2 = list1
list1 is list2
True
list2 = [1, 2, 3]
print(list1 is list2)
print(list1 is not list2)
False
True

6.2 and and or

Combine statements with and and or

if (x >= 0) and (x < 20):
    print('x is in [0, 20)')
x is in [0, 20)
if 0 <= x < 20:
    print('x is in [0, 20)')
x is in [0, 20)

7. Loops

If you want to repeat a task consecutively for the same context

7.1 For loops

Iterate through the elements of a list/tuple/etc

# List/tuple
for lecture in lectures:
    print('Lecture:', lecture)
Lecture: 0
Lecture: 2
Lecture: 3
Lecture: 4
Lecture: 5
Lecture: 6
Lecture: 7
Lecture: 8
lectures_occurred.items()
dict_items([(1, 'True'), (2, 'False'), (3, 'False'), (4, 'False'), (5, 'False'), (6, 'False'), (7, 'False'), (8, 'False'), (0, False), ('word', 'definition')])
# Dict
for lecture, lecture_occurred in lectures_occurred.items():
    print(f'Lecture {lecture} occurred: {lecture_occurred}')
Lecture 1 occurred: True
Lecture 2 occurred: False
Lecture 3 occurred: False
Lecture 4 occurred: False
Lecture 5 occurred: False
Lecture 6 occurred: False
Lecture 7 occurred: False
Lecture 8 occurred: False
Lecture 0 occurred: False
Lecture word occurred: definition
len(lectures)
8
# Range
for i in range(len(lectures)):
    print(f'Loop {i}, lecture {lectures[i]}')
Loop 0, lecture 0
Loop 1, lecture 2
Loop 2, lecture 3
Loop 3, lecture 4
Loop 4, lecture 5
Loop 5, lecture 6
Loop 6, lecture 7
Loop 7, lecture 8
# Enumerate
for i, lecture in enumerate(lectures):
    print(f'Loop {i}, lecture {lecture}')
Loop 0, lecture 0
Loop 1, lecture 2
Loop 2, lecture 3
Loop 3, lecture 4
Loop 4, lecture 5
Loop 5, lecture 6
Loop 6, lecture 7
Loop 7, lecture 8

7.2 While loops

Iterate as long as some condition holds

i = 0
while i < 10:
    print(i)
    i += 1
0
1
2
3
4
5
6
7
8
9

7.3 Breaks

An alternative way to get out of loops

i = 0
while True:
    print(i)
    i += 1
    if i >= 10:
        break
0
1
2
3
4
5
6
7
8
9

7.4 Continue

If you want an if statement for clarity, but you don’t want it to do anything

for i, lecture in enumerate(lectures):
    print(i)
    if lecture == 3:
        continue
    else:
        print('This is not lecture 3')
0
This is not lecture 3
1
This is not lecture 3
2
3
This is not lecture 3
4
This is not lecture 3
5
This is not lecture 3
6
This is not lecture 3
7
This is not lecture 3
for i, lecture in enumerate(lectures):
    print(i)
    if lecture == 3:
    else:
        print('This is not lecture 3')
IndentationError: expected an indented block after 'if' statement on line 3 (3424403967.py, line 4)

8. Functions

If you want to repeat a task, potentially non-consecutively, for potentially different contexts

8.1 Arguments

The input the function requires to run (equivalent to the arguments of a mathematical function)

8.2 Returns

What the function produces after it runs

8.3 Comments

Explain what you code is doing (put # before a single-line comment, or wrap a multi-line comment in triple quotes ''')

8.3.1 Docstrings

Detail at the top of the function what it does, what the arguments are, and what it returns

def square_x(x):
    '''
    Return the square of x.
    
    Arguments:
        x (float): value to square
        
    Returns:
        (float): square of x
    '''
    return x ** 2

def list_mean(lst):
    '''
    Return the mean of a list of numbers.
    
    Arguments:
        lst (list): list to compute the mean of
        
    Returns:
        (float): mean value of lst
    '''
    lst_sum = 0
    lst_len = 0
    for val in lst:
        # Add values to sum
        lst_sum += val
        # Update length of list
        lst_len += 1
    # Compute mean value in lst
    return lst_sum / lst_len

def list_mean_v2(lst):
    '''
    Return the mean of a list of numbers.
    
    Arguments:
        lst (list): list to compute the mean of
        
    Returns:
        (float): mean value of lst
    '''
    return sum(lst) / len(lst)
square_x(10)
100
list_mean([2, 7, 10])
6.333333333333333
list_mean_v2([2, 7, 10])
6.333333333333333
# Two arguments, plus using functions inside other functions
def list_mean_v3(lst1, lst2):
    '''
    Return the mean of the means of two lists of numbers.
    
    Arguments:
        lst1 (list): list 1 to compute the mean of
        lst2 (list): list 2 to compute the mean of

    Returns:
        (float): mean value of mean values of lst1 and lst2
    '''
    return (list_mean_v2(lst1) + list_mean_v2(lst2)) / 2

We write functions to avoid the following:

lst1 = [2, 7, 10]
lst2 = [5, 12, 1]

lst_sum1 = 0
lst_len1 = 0
for val in lst1:
    # Add values to sum
    lst_sum1 += val
    # Update length of list
    lst_len1 += 1
# Compute mean value in lst
lst_mean1 = lst_sum1 / lst_len1

lst_sum2 = 0
lst_len2 = 0
for val in lst2:
    # Add values to sum
    lst_sum2 += val
    # Update length of list
    lst_len2 += 1
# Compute mean value in lst
lst_mean2 = lst_sum2 / lst_len2

print((lst_mean1 + lst_mean2) / 2)
6.166666666666666
list_mean_v3([2, 7, 10], [5, 12, 1])
6.166666666666666

9. Printing text

Useful for debugging

Look throughout for examples, but primarily use f-strings:

print(f'This is an f statement, so we can print variables like lists: {lectures} or dicts: {lectures_occurred} easily')
This is an f statement, so we can print variables like lists: [0, 2, 3, 4, 5, 6, 7, 8] or dicts: {1: 'True', 2: 'False', 3: 'False', 4: 'False', 5: 'False', 6: 'False', 7: 'False', 8: 'False', 0: False, 'word': 'definition'} easily

For simple cases, use commas (this is not as clean for complicated examples):

print('Lectures:', lectures)
Lectures: [0, 2, 3, 4, 5, 6, 7, 8]