For those with Python experience: review, make you aware of some things you may not have seen before - it will not be exhaustive.
For those without Python experience: introduction to Python syntax
Problem Solving with Algorithms and Data Structures using Python, Chapter 1: https://runestone.academy/runestone/books/published/pythonds/Introduction/toctree.html
Sections 1.1-1.4, 1.7, 1.8, 1.10, 1.12
Also see Think Python for a more exhaustive reference of basic Python or A Quick Python tutorial
Python can be run in either script mode or interactive mode
My slides are written using a Jupyter Notebook mixes interactive mode cells and mark-up/documentation cells
print("Hello CS66 Students!")
Hello CS66 Students!
Let's see how script mode and interactive mode works in VSCode
If this works, it could be a useful way to work through in-class activities
Let's try it.
Python data items are called objects.
Examples of types of objects
from Activities 1.8.1.1 and 1.8.1.2
print(2+3*4)
print((2+3)*4)
print(2**10) ## ** is the exponent operator
print(6/3)
print(7/3)
print(7//3) ## integer division
print(7%3) ## remainder (modulo)
print(3/6)
print(3//6)
print(3%6)
print(2**100)
14 20 1024 2.0 2.3333333333333335 2 1 0.5 0 3 1267650600228229401496703205376
print(5==10)
print(10 > 5)
print((5 >= 1) and (5 <= 10))
False True True
Assignments of values to variables in Python is done with the = operator
variables do not need to be declared ahead of time, and their types can change
x = False
print( type(x) )
x = 1
x = x + 1
print( type(x) )
print(x)
<class 'bool'> <class 'int'> 2
Lists are Python's ordered collection type (some other langauges call them arrays)
They are heterogeneous - they can have a mix of object types.
myList = [1,3,True,6.5]
Use subscipt notation to access elements by their index.
Indices are 0-based
print(myList[3])
myList[0] = "hi"
print(myList)
6.5 ['hi', 3, True, 6.5]
There are many different built-in functions and methods that work with lists
myList = [1024, 3, True, 6.5]
myList.append(False) #add on to the end of a list
print(myList)
[1024, 3, True, 6.5, False]
myList.insert(2,4.5) #put a new value at index 2
print(myList)
[1024, 3, 4.5, True, 6.5, False]
print(myList.pop()) #remove and return whatever is at the end
print(myList)
False [1024, 3, 4.5, True, 6.5]
print(myList.pop(1)) #remove and return whatever is at index 1
print(myList)
myList.pop(2)
print(myList)
3 [1024, 4.5, True, 6.5] [1024, 4.5, 6.5]
anotherList = [10,2.5,47,1,6.63]
anotherList.sort() #sort the list
print(anotherList)
[1, 2.5, 6.63, 10, 47]
anotherList = [10,2.5,47,1,6.63]
anotherList.reverse() #reverse the list
print(anotherList)
[6.63, 1, 47, 2.5, 10]
anotherList = [10,47,2.5,47,1,6.63,47]
print(anotherList.count(47)) #count how many times 47 appears
print(anotherList.index(2.5)) #which index is 2.5 at?
3 2
print( 42 in anotherList ) #test if 42 is a member of the list
False
anotherList.remove(2.5) #remove an item by its value
print(anotherList)
[10, 47, 47, 1, 6.63, 47]
#slice the list from index 2 up to (but not including) index 4
print( anotherList[2:4] )
[47, 1]
print( myList + anotherList ) #concatenate two lists
[1024, 4.5, 6.5, 10, 47, 47, 1, 6.63, 47]
print( len(anotherList) ) #find the length of a list
6
Strings and Tuples behave much like lists, but they're immutable - they can't be changed
myTuple = (2,True,4.96)
print( len(myTuple) )
print( myTuple[2] )
3 4.96
myTuple[0] = 10 #error because tuples are immutable
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) Input In [20], in <cell line: 1>() ----> 1 myTuple[0] = 10 TypeError: 'tuple' object does not support item assignment
myString = "Eric"
print( myString[1] )
print( myString.lower() ) #there are many useful string methods
r eric
Here's an example of the syntax for a Python while loop.
counter = 1
while counter <= 5:
print("Hello, world")
counter = counter + 1
Hello, world Hello, world Hello, world Hello, world Hello, world
In Python, tabs matter! You always tab in any block of code associated with a loop, if-statement, function definition, etc.
for loops can be used to iterate through collections
In this example, day is the loop variable that takes on the next value in the list with each iteration.
days_of_the_week = ["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"]
for day in days_of_the_week:
print(day,"is a good day for programming")
Sunday is a good day for programming Monday is a good day for programming Tuesday is a good day for programming Wednesday is a good day for programming Thursday is a good day for programming Friday is a good day for programming Saturday is a good day for programming
range()¶For loops are often combined with the range() function, which allow it to operate as a count-controlled loop.
for num in range(5):
print(num,"squared is",num**2)
0 squared is 0 1 squared is 1 2 squared is 4 3 squared is 9 4 squared is 16
It's also common to use range() with for loops to iterator through the indices of a list rather than the items of the list.
days_of_the_week = ["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"]
for day_num in range(len(days_of_the_week)):
print(days_of_the_week[day_num],"is a good day for programming")
Sunday is a good day for programming Monday is a good day for programming Tuesday is a good day for programming Wednesday is a good day for programming Thursday is a good day for programming Friday is a good day for programming Saturday is a good day for programming
It's easy to mix up whether you're iterating through items or indices, so make sure to think twice about how you're setting up you loops!
Python has if, else, and elif keywords to handle all of your conditional needs.
students = 124
classrooms = 5
if classrooms <= 0:
print("You must have at least one classroom.")
students = 124
classrooms = 5
if classrooms <= 0:
print("You must have at least one classroom.")
else:
print("There are",students/classrooms,"students per classroom.")
There are 24.8 students per classroom.
score = 76
if score >= 90:
print('A')
elif score >=80:
print('B')
elif score >= 70:
print('C')
elif score >= 60:
print('D')
else:
print('F')
C
You can define functions in Python with the def keyword.
Parameters are listed as comma,separated variable names between parentheses.
The return keyword causes the function to terminate, with the given value returned.
def square(n):
return n**2
print( square(3) )
9
square( square(3) )
81
Make a group of 3-4 students.
Have a discussion about each of these problems. Write notes either in this notebook, the comments of a regular Python file, or in some other convenient place.
Run the following code example. In the notes section below, describe what the code does.
anotherList = [10,47,2.5,47,1,6.63,47]
print(anotherList.index(2.5))
you may use this space for your notes
What happens if you try to use the index method for an item that doesn't appear in the list?
## test some code here
write your notes here
How is the list index method different than the in operator?
my_list = [35,66,70,5,42,10,12]
print(42 in my_list)
write your notes here
In the previous activity, you wrote a search_for function which served the same purpose as the in (e.g., list-contains) operator. Now write a similar function called find_index which serves the same purpose as the list index method you worked with above. However, instead of giving an error when the item isn't in the list, return -1 instead.
# write your code here
write your notes here
Write a function called find_index_2D() that will find the position of an item in a 2-dimension list. For example, if called like this:
# write your code here
my_2d_list = [[0,1,2,3],
[10,11,12,13],
[20,21,22,23]]
print( find_index_2D(12,my_2d_list) ) #it should return the tuple (1,2) to indicate it is in row 1, column 2.
write your notes here