import random
Lesson 1
Overview
Self-introductions
Conda
- Environments
Importing packages
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
- Introduction to if statements, loops, and functions
- Concepts
- Shared syntax
- Colons
- Indentation
- If statements
- Comparisons
and
andor
- Loops
- For loops
- While loops
- Breaks
- Continue
- Functions
- Arguments
- Returns
- Comments
- Docstrings
- 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 replacepycourse
with any custom name) - To activate:
conda activate pycourse
- To install pip:
conda install pip
- To install package:
pip install packagename
(replacepackagename
with the name of the package you want to install) - For this lesson, please install:
jupyterlab
and/ornotebook
to be able to open Jupyter Notebooks (like this) (see here for more information)
- For this lesson, please install:
- Link to environment features: Conda environments
2.2 Alternative to Jupyter
#%%
import random
random.random()
3. Importing packages
Type import packagename
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 ==
)
= 10
x print(x)
10
4.2 Naming
Choose names carefully
= 10
x = 10 distance
4.3 Types
str, int, float, bool, lists/tuples/sets, dicts
= 'Python Course, Summer 2024'
course_name_v1 = "Python Course, Summer 2024"
course_name_v2 = \
course_name_v3 '''
Python Course, Summer 2024
'''
= 2024
course_year = 1/5 # Or 0.2
lecture_1_frac_complete = False # Or True
lecture_1_complete = [1, 2, 3, 4, 5, 6, 7, 8] # Mutable
lectures = (1, 2, 3, 4, 5, 6, 7, 8) # Immutable
lecture_v2 = {1, 2, 3, 4, 5, 6, 7, 8, 8}
lectures_v3 = {1: 'True', 2: 'False', 3: 'False', 4: 'False', 5: 'False', 6: 'False', 7: 'False', 8: 'False'} lectures_occurred
4.4 For ints/floats: operations
- Addition:
+
- Subtraction:
-
- Multiplication:
*
- Division:
/
- Exponentiation:
**
- In-place:
+=
,-=
,*=
,/=
,**=
= 5
a = 2.0 b
print(a + b)
7.0
= a + b
a print(a)
7.0
+= b
a print(a)
9.0
= 5
a *= b
a print(a)
10.0
= 5
a **= b
a 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)
0] = 0
lectures[print(lectures)
[1, 2, 3, 4, 5, 6, 7, 8]
[0, 2, 3, 4, 5, 6, 7, 8]
print(lecture_v2)
0] = 0 lecture_v2[
(1, 2, 3, 4, 5, 6, 7, 8)
TypeError: 'tuple' object does not support item assignment
print(lectures_v3)
0] = 0 lectures_v3[
{1, 2, 3, 4, 5, 6, 7, 8}
TypeError: 'set' object does not support item assignment
print(lectures_occurred)
0] = False
lectures_occurred[print(lectures_occurred)
'word'] = 'definition'
lectures_occurred[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
= 'hello'
a 3: 5] a[
'lo'
0] a[
'h'
2:] a[
'llo'
-3:] a[
'llo'
Warning: indexing outside of strings doesn’t raise an error
2:100] a[
'llo'
Strings can be combined using +
= 'hello'
a = 'goodbye'
b + b a
'hellogoodbye'
Variables can easily be put into strings using f-strings
= 5
a = 6
b 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
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 inequalityin
for list membershipis
for variable reference ids andNone
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
= 5
a = (a == 5)
x 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
= [1, 2, 3]
list1 = list1
list2 is list2 list1
True
= [1, 2, 3]
list2 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
= 0
i while i < 10:
print(i)
+= 1 i
0
1
2
3
4
5
6
7
8
9
7.3 Breaks
An alternative way to get out of loops
= 0
i while True:
print(i)
+= 1
i 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
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]
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
We write functions to avoid the following: