Lecture 04: Programming in Python (2 of 3)
Please note: This lecture will be recorded and made available for viewing online. If you do not wish to be recorded, please adjust your camera settings accordingly.
Reminders:
Assignment 1 is due on Thursday night (Jan 14). This is for a grade!
Remember to look for Participation Checks throughout this lecture! Starting this week, Participation Checks will be counted. A review of Participation Checks can be found in Lecture 1, or in the ZulipChat (in the CourseLogistics/Syllabus stream)
Office Hours Schedule can be found in Course links folder. Attend them with any questions about the course/assignments.
For questions on assignments: Please try to understand/play around with the exercises first, before asking questions on them. We are happy to help at any point, but it is much easier to give useful feedback if you have specific questions.
Sections will be held Tuesdays, essentially from 2-5 pm. Sections will review information directly related to homeworks and to the past week(ish) of lectures.
Please ask questions in the chat if you have any!
Conditional Statements in Python
A conditional statement in a piece of code is a "subroutine" that will execute only if a certain statement is true. In Python this works using the "if/elif/else" command. We will start small and build up:
Usually one does not use the "absolute" boolean values True
and False
in a conditional statement, as we already know their truth values. Often we will use a conditional statement as a test on some variable.
The common comparison operators (for numeric values) in Python are:
Equality:
==
Inequality:
!=
Strictly less than:
<
Strictly greater than:
>
Less than or equal to:
<=
Greater than or equal to:
>=
Operators can be chained together using the and
and or
commands. For readability, you can group your individual Boolean expressions using parens, but this is not necessary.
As a reminder, here are the truth tables for and
and or
:
*** Participation Check ***
Recall that modular arithmetic in Python works using the %
operator. In the code cell below there is a for loop written. Fill out the for loop so that it only prints out the integers which are greater than 6 or divisible by 4. If you need more help on the %
operator, perhaps it would be nice to run the loop in the second code cell for a reminder on how %
works.
****************************
You can negate Boolean expressions in Python using the not
command
If, elif, else
Often we will want to do one operation to a value if a certain condition holds, and a different operation to a value if that condition does not hold.
For example, maybe three candidates are running for election. Using a for loop and an if, elif, else statement, you can tally the votes for these candidates:
The elif
statement is optional; you can also write a simple if/else
statement:
Alternatively, you can make a conditional statement more complicated with more elif
statements!
More advanced flow control: strings, lists and sets
Recall that a string in Python is an ordered collection of unicode characters, and a list in Python is an ordered sequence of values. Note: in Python, you do not have to declare the type of elements that a list can contain, and in fact your list can contain several different types of elements:
Another useful way to collect data in Python is a set. Sets are unordered collections of distinct objects.
You can convert a list or string into a set using the set()
command
Similarly you can convert a set or string into a list via the list()
command. This puts an artificial ordering on your set.
Finally, you can turn a list of strings into a single string using the join
command:
Note: str()
is a command which does turn things into strings, but it is a bit funny:
Iteratively updating lists and sets
Lists and sets are mutable in Python. The very simplif meaning you can "mutate" (change) them on the fly.
You can iteratively update lists using the append
or remove
command:
You can iteratively update sets using the add
or remove
commmand:
*** Participation Check ***
In the code cell below there are two empty lists, Evens
and Odds
. Using a for
loop, an if/else
statement, and the append
command, turn Evens
into the list of even integers between 0 and 10 (inclusive) and Odds
into the list of odd integers between 0 and 10.
****************************
You can test for membership in a list, set, or string using the in
command:
Super fun fact! Because a set is unordered, membership testing in a set is much much much faster than in a list:
In fancier terms, a set in Python has constant time lookup whereas a lookup in a list depends on the size of that list. If you ever do an interview for a computer science internship/job, you will need to know that!
Slice Indexing of lists and strings
To get an item of a list/string, you use the following notation: l[i]
returns the item in the list/string at the i
th index. Remember, Python indexing starts at 0.
You can also negate the index i
to obtain elements from the back of the list; this is explored in HW 1.
To obtain a sublist of a list or a substring of a string, use the syntax l[start:end]
for your start and end index. Be careful! Where does it actually end?
This is similar to range(n)
not encompassing the value n
.
You can skip one (or both) of the indices to get everything up to a given point, or everything after a given point:
Finally, there is an optional "step size" which you can use:
Your step size can be negative, in which case the list will reverse! This is also explored in HW 1. For more info, see here: https://realpython.com/lessons/indexing-and-slicing/
Comprehensions
A list comprehension in Python is a beautiful way of creating complicated lists in a short amount of code. Recall the first participation check, where we created the list of even integers from 0 to 10 (inclusive) as well as the list of odd integers in that range.
You can compress this construction down using a list comprehension.
You can apply a function to the variable as well: here is a list of some squares of some even numbers:
Here is a list comprehension syntax breakdown:
For a detailed discussion of list comprehensions, see here: https://realpython.com/list-comprehension-python/
Truthy/falsy
Python syntax allows you to write conditional statements in ways that seem strange, but are very convenient once you get used to it.
In other words, Python automatically interprets
if list1:
to mean "if list1
is nonempty, do something to it." Truthy/falsy objects in Python are explored more in HW 1, and can be useful to exploit.
While Loops
A while loop is similar to a for loop, but it explicitly depends on a conditional statement:
In general, a for
loop is used when you have a predetermined number of operations you want to do, and a while
loop is used to execute some piece of code an arbitrary number of times until something desirable happens. They are often interchangeable, but occasionally a while
loop really is more useful.
For example (if you know what this means), a breadth first search or a depth first search is most easily implemented using a while
loop. We might get into this later on, but I'm not entirely sure yet.