2 CompSci 101L - 10/7/25

0.0(0)
studied byStudied by 0 people
0.0(0)
full-widthCall Kai
learnLearn
examPractice Test
spaced repetitionSpaced Repetition
heart puzzleMatch
flashcardsFlashcards
GameKnowt Play
Card Sorting

1/36

encourage image

There's no tags or description

Looks like no tags are added yet.

Study Analytics
Name
Mastery
Learn
Test
Matching
Spaced

No study sessions yet.

37 Terms

1
New cards

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

  1. 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). 

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

  1. Programmer’s Mental Chunking

  • Tess’s movement can be thought of in two chunks. 

  1. Draw the triangle (lines 12-17). 

  2. Move away from the origin (lines 19-20). 

  • The blank line after 17 makes this chunking clear. 

  • Comments help record these reasoning steps. 

  1. Screen Attributes

  • wn.bgcolor(“lightgreen”) → Sets the background color of the window. 

  • wn.exitonclick() → Keeps the window open until the user clicks it. 

2
New cards

Common ‘turtle’ Methods and Observations

  1. 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). 

  1. Alternative Movement Methods

  • backward(distance) → moves backward

  • alex.backward(-100) → moves alex forward

  1. Pen Control

  1. Turtle Shapes

  • “arrow”, “blank”, “circle”, “classic”, “square”, “triangle”, “turtle”

  • alex.shape(“turtle”)


  1. Speed Control

  • Speed Settings: 1 (slowest) → 10 (fastest)

  • speed(0) → no animation (instant drawing)

  • alex.speed(10


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

3
New cards

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.

  1. Basic Form — range(stop)
    Produces integers starting at 0, up to but not including ‘stop’.
    for i in range(4): print(i)

  2. Two-Parameter Form — range(start, stop)
    Produces numbers starting at ‘start’, up to but not including ‘stop’.
    print(list(range(1, 5)))

  3. 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]

4
New cards

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.

5
New cards

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

6
New cards

Lists and the ‘for’ Loop

7
New cards

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.

8
New cards

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

9
New cards

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.

10
New cards

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

11
New cards

Alternative File Reading Methods

12
New cards

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

13
New cards

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.

14
New cards

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. 

15
New cards

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. 

16
New cards

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: 

  1. Test by Printing

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

17
New cards

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.

18
New cards

Randomly Walking Turtle

19
New cards

The 3n + 1 Sequence

s

20
New cards

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

21
New cards

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.

22
New cards

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.

23
New cards

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. 

24
New cards

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.

25
New cards

‘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).

26
New cards

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

27
New cards

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.

28
New cards

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.

29
New cards

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 {}. 

30
New cards

Creating — Set

31
New cards

Add / Update — Set

32
New cards

Membership / Size / Emptiness — Set

33
New cards

Remove Elements — Set

34
New cards

Iterate — Set (Order not Defined)

35
New cards

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

36
New cards

Subset / Superset Tests & Copy / Comprehension — Set

37
New cards

Set — Practice Problems