1/36
Looks like no tags are added yet.
Name | Mastery | Learn | Test | Matching | Spaced |
|---|
No study sessions yet.
Turtle Graphics
A module that allows you to create a virtual “turtle” object that can move around.
import turtle — allows us to use the turtles library, loads the turtle graphics module, gives us access to Turtle and Screen (the drawing canvas)
wn = turtle.Screen() — creates a graphics window where the turtle will draw, variable ‘wn’ refers to the screen object
alex = turtle.Turtle() — creates a turtle named alex

Instances of a Class
Each turtle (alex, tess) is an independent object.
They are both instances of the Turtle type (class).
Each instance has its own attributes (color, pen size, position, direction) and its own methods (like forward, left).
Angles and Completeness of Shape
A full circle = 360 degrees
Even if the final turn seems redundant, including it → ensures the turtle ends facing the same direction it started, and makes it easier for humans to reason about and build larger programs.
Programmer’s Mental Chunking
Tess’s movement can be thought of in two chunks.
Draw the triangle (lines 12-17).
Move away from the origin (lines 19-20).
The blank line after 17 makes this chunking clear.
Comments help record these reasoning steps.
Screen Attributes
wn.bgcolor(“lightgreen”) → Sets the background color of the window.
wn.exitonclick() → Keeps the window open until the user clicks it.
Common ‘turtle’ Methods and Observations
Negative Angles and Distances
Negative Distance → tess.forward(-100) → moves tess backward
Negative Angle → tess.left(-30) → turns tess right 30 degrees
Turning left 30 degrees is the same as turning right 330 degrees (because 360 degrees is a circle).
Alternative Movement Methods
backward(distance) → moves backward
alex.backward(-100) → moves alex forward
Pen Control

Turtle Shapes
“arrow”, “blank”, “circle”, “classic”, “square”, “triangle”, “turtle”
alex.shape(“turtle”)
Speed Control
Speed Settings: 1 (slowest) → 10 (fastest)
speed(0) → no animation (instant drawing)
alex.speed(10
Stamping
A turtle can leave footprints that remain on the canvas.
tess.stamp()
Works even when the pen is up.
Useful for patterns where you want multiple turtle shapes but only one real turtle.

The ‘range’ Function
A built-in Python function that generates a sequence of numbers. It is commonly used in ‘for’ loops to specify the number of iterations.
Generating lists of numbers is a great alternative to manually writing out a list of numbers.
Basic Form — range(stop)
Produces integers starting at 0, up to but not including ‘stop’.
for i in range(4): print(i)
Two-Parameter Form — range(start, stop)
Produces numbers starting at ‘start’, up to but not including ‘stop’.
print(list(range(1, 5)))
Three-Parameter Form — range(start, stop, step)
Adds a step to control how numbers increase (or decrease).
Negative steps let you count backwards.
Lazy Evaluation — ‘range’ does not immediately create a full list of numbers.
It generates values when needed.
print(range(4)) → shows something like: range(0, 4)
To see all the elements, wrap with list().
print(list(range(4))) → [0, 1, 2, 3]
Traversal and the ‘for’ Loop — By Index
Strings are sequences, so you can access characters by index. You can use ‘range’ to generate a list of index positions.

Reversing Traversal with the ‘for’ Loop — Using ‘range(start, stop, step)’ to Go Backwards

Lists and the ‘for’ Loop

Files in Python
Collections of data stored on a computer, which can be accessed and manipulated by programs and users.
Files as Objects — Once opened, a file becomes a Python object, just like lists, strings, or turtles.
You must open before use and close when finished.

Finding a File on your Disk
Filename → short name (eg, hello.txt)
Path → full name, describes the file’s location on the disk → /Users/yourname/hello.txt

File Objects
open() returns a file object.
Stored in a variable (eg ‘fileref’).
Methods of a File Object:
.read() → read whole file
.readline() → read one line at a time
.readlines() → read all lines into a list
Why Close the File?
Always call .close() when done.
After closing, attempts to use ‘fileref’ will cause an error.
Good practice, frees memory and system resources.

Iterating Over Lines in a File
Processing Text Files — Iterating through each line using a ‘for’ loop.
Since text files are stored as sequences of lines (each ending with a newline character \n), Python makes it easy to handle them line by line.
Newline Character (\n) — Marks the end of each line in a file. You don’t see it when printing, but it is there.
Looping Through a File:
for line in myFile:
# process the line

Alternative File Reading Methods

Alternative File Reading Methods — readline()
Returns the next line of the file as a string, with all text up to and including the newline character. If ‘n’ is provided as a parameter, then only ‘n’ characters will be returned if the line is longer than ‘n’.

Alternative File Reading Methods — readlines()
Returns all lines as a list in the form of a list of strings, each representing a single line of the file. If ‘n’ is not provided, then all lines of the file are returned. If ‘n’ is provided, then ‘n’ characters are read but ‘n’ is rounded up so that an entire line is returned.
Each line has a newline character included at the end.

Alternative File Reading Methods — read()
Returns the entire file as one large string, including the newline characters. Useful for treating the file as raw text.

Priming Read
Needed before the loop so ‘line’ has an initial value for the ‘while’ condition. It is a technique used to read the first line before entering a loop, ensuring that the loop can execute correctly by providing a starting value.

Line 2 → Priming Read
Needed before the loop so ‘line’ has an initial value for the ‘while’ condition.
The ‘readline’ method will return the empty string if there is no more data in the file.
Line 3 → ‘while line:’
Python is looking for a Boolean condition.
False → If it receives an empty string.
True → If it receives a non-empty string.
Line 6 → Reassigning ‘line’
This statement will reassign the variable ‘line’ to the next line of the file.
Without this, there would be an infinite loop processing the same line of data continuously.
Writing Text Files
Writing Mode (‘w’) → When opening a file with ‘open(filename, ‘w’)’, Python creates a new empty file for writing. If the file already exists, it is cleared (previous contents are erased).
‘write()’ Method → Adds a string to a file. Unlike ‘print()’, it does not automatically add a newline; the programmer must include \n manually if line breaks are desired.
Output File → A text file created by your program to store processed or reformatted data for later use.
The Process:
Opening a file for reading versus writing.
Reading → open("ccdata.txt", "r")
Writing → open("emissiondata.txt", "w")
Preparing the data to write.
Read each line of the input file.
Use ‘.split()’ to break it into pieces.
Build a string that has only the values you need (in this case, year and emission).
Printing versus writing.
Start by printing to screen to test formatting.
Replace print() with outfile.write( … ) once satisfied.
Always add \n so each entry appears on its own line.
Example:
Test by Printing

Write to a New File

This produces a new file ‘emissiondata.txt’, containing the year and emission data neatly formatted.
Use ‘w’ to open files for writing.
‘write()’ requires strings → always add \n yourself for newlines.
A good workflow is:
Read original data.
Process to extract what’s needed.
Write processed results into a new file.
Always close both input and output files when finished.
The ‘while’ Statement
‘while’ Statement → A Python loop that repeats a block of code as long as a Boolean condition is ‘True’.
Infinite Loop → A loop that never terminates because the condition never becomes ‘False’.
Definite Iteration → Iteration where the number of repetitions is known in advance (‘for’ loop).
Indefinite Iteration → Iteration where the number of repetitions is not known in advance; depends on a condition (‘while’ loop).
Loop Body → The indented block of code executed on each pass through the loop.
How the ‘while’ Statement Works:
The ‘while’ loop evaluates a condition.
If the condition is ‘True’, the loop body executes.
After the body finishes, the condition is checked again.
The cycle continues until the condition is ‘False’.
If the condition is ‘False’ the first time, the loop body never runs.

Randomly Walking Turtle

The 3n + 1 Sequence
s

Other Uses of ‘while’ — Sentinel Value
A special value that signals the end of input (e.g., 0 meaning “no more items”).

In this program, 0 is the sentinel to stop the loop. ‘total’ accumulates the sum, ‘count’ keeps track of the items.
‘average’ is computed at the end.
Problems with this Program:
Negative numbers → should display an error instead of being added.
Zero as first input → division by zero error (needs handling).
Prices should be displayed to two decimal places.
ValueError can arise if something is received as a string that cannot be converted to a float, like ‘None’.
Other Uses of ‘while’ — Validating the Input

You can also use a ‘while’ loop when you want to validate input.
When you want to make sure the user has entered valid input for a prompt.
Here is a program that uses a ‘while’ loop to keep asking until it receives a valid answer.



Result List Pattern
A common structure for building lists inside a function.
Initialize an empty list.
Loop through a sequence or range.
Generate / compute new elements.
Append them to the list.
Return the list.
Constructing and Returning Lists:
Start with result = [].
Return result at the end.

List Comprehensions
A concise way to create lists in Python by applying an expression to each item in an iterable, optionally filtering elements with a conditional statement.

Rewriting ‘primes_upto’ with List Comprehension:

Iterates over numbers 2 through n-1.
Keeps only numbers where is_prime(num) returns True.
Builds and returns the complete list in one line.

Short-Circuit Evaluation
Python does not always evaluate both sides of a logical expression (and / or). It only evaluates as much as necessary to determine the outcome.
‘and’ → If the first condition is False, the entire expression must be False. Python skips checking the second condition.
‘or’ → If the first condition is True, the entire expression must be True. Python skips checking the second condition.
This makes Python logical expressions both efficient and safe, because the second condition only executes if it’s actually needed.
‘list’ Type Conversion Function
list() Function → Converts a sequence (like a string, tuple, or range) into a list.
Each element in the original sequence becomes an element in the new list.
For strings, this means every character (including spaces) becomes a list element.
Limitations: The argument must be a sequence. You cannot use list() on something that is not iterable (like an integer).

Tuples and Mutability
Tuples → Like lists, they hold items of any type – but like strings, they are immutable.
Purpose:
Often used like records → grouping together related information (like a student record).
They allow you to treat multiple related fields as a single unit.
Operations:
Tuples support the same sequence operations as lists and strings.
Indexing → julia[2] → 1967
Slicing → julia[2:6] → (1967, ‘Duplicity’, 2009, ‘Actress’)
len() → to get length
Iteration with a ‘for’ loop.
Immutability:
julia[0] = “x” → TypeError
You cannot change tuple elements directly.
julia = julia[:3] + ("Eat Pray Love", 2010) + julia[5:]
But, you can reassign a variable to a new tuple by slicing and concatenating.
Special Case → Single-Element Tuples
Must include a trailing comma, otherwise it is treated as an integer in parentheses.
tup = (5,) → tuple
x = (5) → integer
Tuple Assignment
Python allows you to assign values from a tuple directly into a tuple of variables in a single line.
(name, surname, birth_year, movie, movie_year, profession, birth_place) = julia
This unpacks the elements of ‘julia’ into separate variables. Equivalent to writing seven separate assignment statements.
Requirements:
The number of variables on the left must match the number of elements in the tuple on the right.
Otherwise, Python raises a ValueError.
Swapping Variables:
Normally requires a temporary value.
With tuple assignments, it is much simpler. All right-side expressions are evaluated first, then assigned to the left-side variables.


Tuples as Return Values
Why use Tuples in Functions?
A function in Python can only return one value.
To return multiple related results, we can group them into a tuple.
Highest and lowest scores of a player.
Mean and SD of data.
Data broken into year, month, day.


Set
List → A group of ordered elements that have a first element, a second element, etc.
Set → A group of unordered elements. Each element can only appear once in a set.
Not indexable (no s[0]), order is not guaranteed.
Elements must be hashable (e.g., int, float, str, tuple of hashables).
What is not allowed is list, dict, set.
Can be created by:
y = set([8, 5, 9, 2, 5])
y = {8, 5, 9, 2, 5}
The set ‘y’ would have four elements → 2, 5, 8, and 9. Even though the set was created with two 5’s, only 1 was stored in the set. The set only stores unique elements.
If we were to print ‘y’, you would get something like this, and the numbers can be in any order → {8, 2, 9, 5}.
print(y[2]) → error, cannot index into a set
You can iterate over all the elements in a set using a ‘for’ loop.
for elem in y:
print(y)
You don’t know how the elements will be printed out, but you know each element will be printed once. The output might be:
9
2
8
5

Tips:
Use sets to deduplicate quickly → unique = set(lst).
Fast membership → x in s is typically O(1) on average
Set order is arbitrary; do not rely on it. Use sorted(s) if needed.
No indexing / slicing.
An empty set is set(), not {}.
Creating — Set

Add / Update — Set

Membership / Size / Emptiness — Set

Remove Elements — Set

Iterate — Set (Order not Defined)

Set Operations (methods, operators, and in-place updates)

Subset / Superset Tests & Copy / Comprehension — Set

Set — Practice Problems



