Download presentation
Presentation is loading. Please wait.
1
CS-104 Final Exam Review Victor Norman
2
Overview Multiple choice – 55 questions.
Lots of “Is there a syntax error in the following code?” questions. Covers everything from 1st day to last day.
3
Topics that will be covered
Assignment statements Arithmetic expressions For loops, with range() Function definitions Function calls and method calls. Accumulator pattern boolean expressions while loops if statements, if-else, if-elif-else, etc. creating lists, indexing, slicing, searching with “in”, appending. tuples: creating, indexing, assigning. strings: creating, indexing, concatenating, etc. class definitions Object-oriented programming terminology: classes, objects, instances, subclass, superclass, instance variable, attribute, method, self, is-a, has-a, inherits, constructor… Implementing __str__, __init__, __add__, etc. Ability to follow logic of code. mutable/immutable types. Optional parameters with default values.
4
Assignment Statements, Arithmetic Expr.
variable-on-left = expression-on-right variable must have proper format: letters, digits, underscores not starting with digit. value + value, or -, *, /, //, %, ** produces an integer or float
5
For loops and range() for loopVar in sequence: statements (aka body)
loopVar is set to first item in the sequence, then 2nd item, then 3rd, etc. range(start, stop, step): generates a sequence of integers starting at start, and stopping before stop, going up by step each time. start is optional: uses 0. step is optional: uses 1.
6
Item-based vs. index-based loops.
for item in sequence: (e.g., list or string) item will refer to the item in the sequence each time. Won’t be able to tell where in the sequence the item is. for idx in range(len(sequence)): range(len(sequence)) converts sequence into a list of indices to index into the sequence from beginning to end. use sequence[idx] in the loop.
7
Functions Before calling a function, you have to define it.
Functions usually return a computed value. Or don’t, but make the Scribbler move, or print something. You must either store the result or print it or use it for something! e.g., y = sin(x) is good. sin(x) is not useful. When calling a function, you are passing values in. The function refers to those values with its parameters.
8
Function definitions def funcName(parameter-list): statements (body of the function) parameters must be legal identifiers (like variables). parameters refer to the values being passed in from the caller. statements compute some value. May use temporary variables. usually return some computed value at the end. parameters and variables defined in the function do not exist after the function call returns.
9
Accumulator pattern Very common pattern in programming, with this general format: accVar = 0 (or [ ] or 1 or “”) for loopVar in sequence: if something(loopVar): accVar = accVar someoperator loopVar # e.g., accVar = accVar + loopVar Example: given list of values, create a string that has all of the values concatenated together: def stringify(aList): res = “” for item in aList: res = res + str(item) return res
10
Boolean expressions <somevalue> == <somevalue> or !=, <, >, <=, >=. results in a True or False value can combine with logical operators: and, or, not similar to and, or, and not gates in ENGR. have to have a true-blue boolean expression on each side of and or or. x < y and x > z Can’t do x < y and > z
11
while loops while booleanExpression : statements
Loops as long as booleanExpression is True – an indeterminate number of times. If in the loop you do not change some variable being used in the expression, the while loop will loop infinitely.
12
break and continue Only used inside of a loop – for loop or while loop – and almost only ever useful inside of a if statement (or else/elif) in a loop. break transfers control to the statement after the loop: the loop is “broken out of” and the code continues executing after the loop. continue transfer control back up to the top of the loop: to the next iteration of the loop.
13
if statements if booleanExpression: statements # one-way decision: do this or do nothing. statements # two-way decision: do this or do the other. else: statements statements # n-way decision: do one of the things that is true elif booleanExpression: statements … else: # optional statements
14
Lists anyoneWannaPlay = [ 10, “s”, “n”, “e”, 1 ]
Hold multiple items of any types in order. Can be indexed, starting at 0, and going to n-1, or using negatives. anyoneWannaPlay[2] is ”n” Is mutable: can be changed after creation: anyoneWannaPlay[-1] = 2 Methods on it: append(), sort(), remove(), pop(), insert(), etc. All methods above return None, except pop, which returns the item that was removed.
15
Lists (continued) Can search if an item is in the list with in: if 17 in listofNums: Can do slicing on it to get a new list from the list: anyoneWannaPlay = [ 10, “s”, “n”, “e”, 1 ] print(anyoneWannaPlay[0:2] + anyoneWannaPlay[3:])
16
Tuples Just like a list, but immutable: cannot change after creation.
Not used often, but can be useful for representing x, y coordinates, r, g, b colors, etc. Create with parens and , : color = (127, 33, 33) Can break a tuple apart with multiple assignment: red, green, blue = color # red is 127, green 33, blue 33.
17
strings Like a list, but contains only single characters.
Create with single, double, triple-single, or triple-double quotes. name = ”Jared” (or ‘Jared’ or ‘’’Jared’’’ or “””Jared”””) Can be indexed (from 0 to n-1) to get a single character or can be sliced: nickname = name[0:2] Immutable: every method that seems to modify it actually creates a new string: capitalize(), upper(), lower(), etc. Can search with in. Can concatenate with other strings: print(name + “ Jones”)
18
classes A class definition defines a new type. class Student:
Contains the functionality (methods) that can be done on an instance of the class. Contains the data the objects contains. class Student: def __init__(self, name, id): self._name = name self._id = id mary = Student(“Mary”, )
19
getters, setters Typically created for each instance variable:
def get_name(self): return self._name def set_name(self, new_name): self._name = new_name Similarly for self._id A.k.a. accessors and mutators
20
self An object refers to itself as self in code in the class definition. The object has another name in code outside of the class definition. joe = Student(“Joe Jones”, ) joe.set_name(“Joseph Jones”) set_name() code refers to the object as self.
21
Overriding built-in functionality
A class can define __str__ so that when an object is “string-ified”, this method is called. print() calls str(val) for each value it needs to print. __str__ must return a string representation of the object. You can implement __add__() if you want to allow the user to add two objects of your class together.
22
Optional parameters with default values
Often a constructor is defined such that you can provide no values and get default values used, or you can provide initial values: class Student: def __init__(self, name=“Namey McNameface”, id=0): self._name = name self._id = id noname = Student() hiro = Student(“Hiro Nakayama”, )
23
Inheritancce You should know what it means and why it is useful.
You should know how you code it up. Know how to call the super-class constructor.
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.