Contact
CoCalc Logo Icon
StoreFeaturesDocsShareSupport News AboutSign UpSign In
| Download
Views: 280
Image: ubuntu2004
Kernel: Python 3 (system-wide)

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:

if True: print('Printing!')
Printing!
if False: print('Printing!')

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.

x = 5 if x < 3: print('Printing')
x = 2 if x < 3: print('Printing')
Printing

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:

TTables

x = 17 if (x < 5) or (x >= 12): print(x)
17
z = 1 y = 43 if z > 0 and y <= 400: print(y-z)
42
if z > 1 and y <= 400: print(y-z)

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

for i in range(20): #Insert your code here if i > 6 or i % 4 == 0: print(i)
0 4 7 8 9 10 11 12 13 14 15 16 17 18 19
for i in range(20): print('i equals {} and i mod 4 equals {}'.format(i,i%4))
i equals 0 and i mod 4 equals 0 i equals 1 and i mod 4 equals 1 i equals 2 and i mod 4 equals 2 i equals 3 and i mod 4 equals 3 i equals 4 and i mod 4 equals 0 i equals 5 and i mod 4 equals 1 i equals 6 and i mod 4 equals 2 i equals 7 and i mod 4 equals 3 i equals 8 and i mod 4 equals 0 i equals 9 and i mod 4 equals 1 i equals 10 and i mod 4 equals 2 i equals 11 and i mod 4 equals 3 i equals 12 and i mod 4 equals 0 i equals 13 and i mod 4 equals 1 i equals 14 and i mod 4 equals 2 i equals 15 and i mod 4 equals 3 i equals 16 and i mod 4 equals 0 i equals 17 and i mod 4 equals 1 i equals 18 and i mod 4 equals 2 i equals 19 and i mod 4 equals 3

****************************

You can negate Boolean expressions in Python using the not command

x = 4 print(x == 4)
True
print(not x == 4)
False
print(x != 4)
False
print(not x!=4)
True

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 i in range(8): if i < 2: print(i,' is smaller than 2') elif 2 <= i and i < 5: print(i,' is between 2 and 4') else: print(i,' is larger than 4')
0 is smaller than 2 1 is smaller than 2 2 is between 2 and 4 3 is between 2 and 4 4 is between 2 and 4 5 is larger than 4 6 is larger than 4 7 is larger than 4

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:

votes = ['Alice', 'Bob', 'Alice','Alice', 'Bob', 'Carl', 'Alice', 'Bob','Alice'] aliceVotes = 0 bobVotes = 0 carlVotes = 0 for vote in votes: if vote == 'Alice': aliceVotes += 1 #Here the += 1 is used to increment the variable. It is equivalent to aliceVotes = aliceVotes + 1 elif vote == 'Bob': bobVotes += 1 else: carlVotes += 1 print('Number of votes for Alice:', aliceVotes) print('Number of votes for Bob:', bobVotes) print('Number of votes for Carl:', carlVotes)
Number of votes for Alice: 5 Number of votes for Bob: 3 Number of votes for Carl: 1

The elif statement is optional; you can also write a simple if/else statement:

votes = ['Alice', 'Bob', 'Alice','Alice', 'Bob', 'Carl', 'Alice', 'Bob','Alice'] aliceVotes = 0 otherVotes = 0 for vote in votes: if vote == 'Alice': aliceVotes += 1 else: otherVotes += 1 print('Number of votes for Alice:', aliceVotes) print('Number of votes for other candidates: ',otherVotes)
Number of votes for Alice: 5 Number of votes for other candidates: 4

Alternatively, you can make a conditional statement more complicated with more elif statements!

for i in range(10): if i == 0: print('Zero') elif i == 1: print('One') elif i == 2: print('Two') elif i == 3: print('Three') elif i == 4: print('Four') elif i == 5: print('Five') elif i == 6: print('Six') elif i == 7: print('Seven') elif i == 8: print('Eight') else: print('Nine')
Zero One Two Three Four Five Six Seven Eight Nine

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:

myString = 'abcdefg' myList = [1,2,3,'Alice','Bob','Carl']

Another useful way to collect data in Python is a set. Sets are unordered collections of distinct objects.

mySet = {1,2,3,3} #You can declare a set using curly braces print(mySet) #Note that when the set prints, the duplicate 3 has been removed!
{1, 2, 3}

You can convert a list or string into a set using the set() command

myNewList = [2,1,3,3] myNewSet = set(myNewList) print(myNewList) print(myNewSet)
[2, 1, 3, 3] {1, 2, 3}

Similarly you can convert a set or string into a list via the list() command. This puts an artificial ordering on your set.

mySet = {'a',3,2} myString = 'Apple' list1 = list(mySet) list2 = list(myString)
print(list1) print(list2)
[2, 3, 'a'] ['A', 'p', 'p', 'l', 'e']

Finally, you can turn a list of strings into a single string using the join command:

''.join(list2)
'Apple'
'@'.join(list2)
'A@p@p@l@e'
data = ['userID','Domain.edu'] '@'.join(data)

Note: str() is a command which does turn things into strings, but it is a bit funny:

print(list1) string = str(list1) print(string)
[2, 3, 'a'] [2, 3, 'a']
for char in string: print(char)
[ 2 , 3 , ' a ' ]

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:

myList = [1,2,3] print(myList) myList.append(6) print(myList) myList.remove(2) print(myList)
[1, 2, 3] [1, 2, 3, 6] [1, 3, 6]

You can iteratively update sets using the add or remove commmand:

mySet = {1,2,3} print(mySet) mySet.add(6) print(mySet) mySet.remove(2) print(mySet)
{1, 2, 3} {1, 2, 3, 6} {1, 3, 6}

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

Evens = [] Odds = [] #Your code goes here for i in range (11): if i % 2 == 0: Evens.append(i) else: Odds.append(i)
#Print both lists by running this cell to check your answer print(Evens) print(Odds)
[0, 2, 4, 6, 8, 10] [1, 3, 5, 7, 9]

****************************

You can test for membership in a list, set, or string using the in command:

mySet = {1,2,3} 2 in mySet
True
myList = [4,6,8] 3 in myList
False
myString = 'taco' 'c' in myString
True

Super fun fact! Because a set is unordered, membership testing in a set is much much much faster than in a list:

mySet = {i for i in range(50000)} myList = [i for i in range(50000)]
for i in range(50000): boolean = i in myList
for i in range(50000): boolean = i in mySet

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 ith index. Remember, Python indexing starts at 0.

l = ['Apple','Banana','Pineapple','Raspberry'] print(l[0]) print(l[1]) print(l[2]) print(l[3])
Apple Banana Pineapple Raspberry
string = 'Apple' print(string[0]) print(string[1]) print(string[2]) print(string[3]) print(string[4])
A p p l e

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?

l = ['Apple','Banana','Pineapple','Raspberry'] print(l[1:3])
['Banana', 'Pineapple']

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:

l = ['Apple','Banana','Pineapple','Raspberry'] print(l[1:]) print(l[:3])
['Banana', 'Pineapple', 'Raspberry'] ['Apple', 'Banana', 'Pineapple']

Finally, there is an optional "step size" which you can use:

l = [1,2,3,4,5,6,7,8,9,10] print(l[:9:2])
[1, 3, 5, 7, 9]

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.

Evens = [] Odds = [] for i in range(0,11): if i%2 == 0: Evens.append(i) else: Odds.append(i) print(Evens) print(Odds)
[0, 2, 4, 6, 8, 10] [1, 3, 5, 7, 9]

You can compress this construction down using a list comprehension.

Evens = [i for i in range(11) if i% 2 == 0] Odds = [i for i in range(11) if i%2 != 0] print(Evens) print(Odds)
[0, 2, 4, 6, 8, 10] [1, 3, 5, 7, 9]

You can apply a function to the variable as well: here is a list of some squares of some even numbers:

SquaredEvens = [i**2 for i in range(11) if i%2 ==0] print(SquaredEvens)
[0, 4, 16, 36, 64, 100]

Here is a list comprehension syntax breakdown:

list comprehensions

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.

list1 = [] list2= [5]
if list1: print('This list is not empty') else: print('This list was empty')
This list was empty
if list2: print('This list is not empty') else: print('This list was empty')
This list is not empty

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:

i = 0 while i < 10: print(i) i = i+1
0 1 2 3 4 5 6 7 8 9
myList = [0,1,2,3,4,5] while myList: x = myList[0] myList.remove(x) print(x**2)
0 1 4 9 16 25

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.

Next time: User defined functions in Python, dictionaries, maybe some other random stuff