Compsci exam notes Flashcards

1
Q

Variables

A

A variable is a named storage location in a computer program.
Different types of variables are used to store different data types.
To define a variable, you need to specify its name and initial value.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Assignment Statement

A

Use the assignment statement ‘=’ to place a new value into a variable.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Assignment Statement Example

A

cansPerPack = 6
Note: ‘=’ is not used for comparison; it copies the value on the right into the variable on the left.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Variable Types

A

There are three types of data in Python: integers (int), floating-point numbers (float), and strings.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Variable Types Examples

A

cansPerPack = 6 # int, canVolume = 12.0 # float

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

Updating a Variable

A

If an existing variable is assigned a new value, that value replaces the previous contents.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

Updated Variable Example

A

cansPerPack = 6 and then cansPerPack = 8
Computed update: cansPerPack = cansPerPack + 2

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

Variable Naming

A

Variable names should describe the purpose of the variable.
Follow rules: start with a letter or underscore, continue with letters, digits, or underscore.
Use ‘camelCase’ notation, avoid reserved words.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

Constants

A

In Python, a constant is a variable whose value should not change after the initial assignment.
Constants are conventionally named in ALL_CAPS.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

Arithmetic Operations

A

Python supports basic arithmetic operations: addition ‘+’, subtraction ‘-‘, multiplication ‘*’, division ‘/’.
Precedence follows PEMDAS (Parenthesis, Exponent, Multiply/Divide, Add/Subtract).
Mixing numeric types results in a floating-point value.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

Arithmetic Operations (Contd.)

A

Use ‘**’ for exponentiation.
Floor division (//) discards the fractional part.
Remainder calculation uses the ‘%’ operator.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

Arithmetic Operations (Contd.) Example

A

Convert pennies to dollars and cents
pennies = 1729
dollars = pennies // 100 # Calculates the number of dollars
cents = pennies % 100 # Calculates the number of pennies
print(“I have”, dollars, “and”, cents, “cents”)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

Math Module

A

Python’s standard library includes the math module for advanced mathematical functions.
Import functions using from math import sqrt.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

Strings

A

Strings are sequences of characters in Python.
Use single or double quotes to define string literals.
String length is obtained using len().

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

String Operations

A

Concatenate strings using ‘+’. Example: firstName + lastName
Repetition using ‘*’. Example: “-“ * 50
Convert numbers to strings using str().

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

String Methods

A

strings have built-in methods like upper(), lower(), etc.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

String Methods Example

A

Example: name.upper() converts all characters to uppercase.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

Input and Output

A

Use input() to read from the console.
Format output using % format specifiers.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

Commenting Code

A

Use comments for explanation and documentation.
Two common styles include starting each line with # or using “”” “”” for multiline comments.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
20
Q

The if Statement

A

Allows a program to execute different actions based on data.
Keywords: if and else.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
21
Q

The if Statement example

A

floor = int(input(“Enter floor number: “))
if floor > 13:
actualFloor = floor - 1
else:
actualFloor = floor
print(“The elevator will travel to the actual floor %d” % actualFloor)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
22
Q

Relational Operators

A

Used in if statements for comparisons.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
23
Q

Floating Point Considerations

A

Floating-point numbers may have precision issues.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
23
Q

Relational Operators Examples

A

if floor > 13:
if floor >= 13:
if floor < 13:
if floor <= 13:
if floor == 13:
if floor != 13:

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
24
Floating Point Considerations Examples
EPSILON = 1E-14 r = math.sqrt(2.0) if abs(r * r - 2.0) < EPSILON: print("sqrt(2.0) squared is approximately 2.0")
25
String Comparison
Strings compared lexicographically.
26
String Comparison Examples
if name1 == name2: print("The strings are identical") if name1 != name2: print("The strings are not identical")
27
Nested Branches
Using nested if statements for multiple conditions.
28
Nested Branches Examples
if maritalStatus == "s": if income <= RATE1_SINGLE_LIMIT: tax1 = RATE1 * income else: tax1 = RATE1 * RATE1_SINGLE_LIMIT tax2 = RATE2 * (income - RATE1_SINGLE_LIMIT) else: # Handle married case similarly
29
Multiple Alternatives
Using if, elif, and else for multiple conditions
30
Input Validation Example
floor = int(input("Enter floor number: ")) if floor == 13: print("Error: There is no thirteenth floor.") elif floor <= 0 or floor > 20: print("Error: The floor must be between 1 and 20.") else:
31
Multiple Alternatives Example
if richter >= 8.0: print("Most structures fall") elif richter >= 7.0: print("Many buildings destroyed") elif richter >= 6.0: print("Many buildings damaged, some collapse") else: print("No destruction of buildings")
32
Input Validation
Ensuring valid user input
33
The while Loop
A while loop is a control structure that repeats a set of instructions as long as a specific condition is true.
34
The while Loop Example
balance = 10.0 target = 100.0 year = 0 rate = 0.025 while balance < target: year += 1 interest = balance * rate / 100 balance += interest
35
Sentinel Values
Sentinel values are special characters or numbers used to indicate the end of a data set.
36
Sentinel Values Example
salary = 0.0 while salary >= 0: salary = float(input()) if salary >= 0.0: total += salary count += 1
37
The for Loop
The for loop is used to iterate over the contents of a container or as a count-controlled loop.
37
Common Loop Algorithms Examples
uppercase = 0 for char in my_string: if char.isupper(): uppercase += 1
38
The for Loop Example
state_name = "Virginia" for letter in state_name: print(letter)
39
Nested Loops Example
for i in range(4): for j in range(i + 1): print("*", end=" ") print()
40
Nested Loops
Nested loops are loops inside other loops. Useful for complex iterations, like processing cells in a table.
41
Processing Strings Example
vowels = 0 for char in word: if char.lower() in "aeiou": vowels += 1
42
Random Numbers & Simulation Example
from random import randint for i in range(10): d1 = randint(1, 6) d2 = randint(1, 6) print(f"Dice 1 is: {d1} and Dice 2 is {d2}")
43
Functions as Black Boxes
Functions Overview Definition: A function is a named sequence of instructions.
44
Functions as Black Boxes Example
def square(number): return number ** 2
45
Function Call
Calling a function executes its instructions.
46
Function Call Example
result = square(5) # Calls the square function with 5 as an argument
47
Implementing & Testing Functions
A function consists of a header (name and parameters) and a body (instructions).
48
Implementing & Testing Functions Example
def greet(name): return f"Hello, {name}!"
49
Testing a Function
To test a function, call it with specific inputs and check the output.
50
Testing a Function Example
greeting = greet("Alice")
51
Parameter Passing
Parameters are inputs passed to a function.
52
Parameter Passing Example
def add(a, b): return a + b
53
Sentinel Values
Sentinel values are special inputs to indicate the end of data.
54
Sentinel Values Example
total = 0 while salary >= 0: salary = float(input()) if salary >= 0: total += salary
55
Functions with & without Return Values
Return Statement Definition: The return statement ends a function and sends a value back
56
Functions with & without Return Values Example
def cube_volume(side_length): return side_length ** 3
57
No Return Value
Functions are not required to return a value.
58
No Return Value Example
def greet(name): print(f"Hello, {name}!")
59
Variable Scope Scope of Variables
The scope of a variable is where it's visible.
59
Stepwise Refinement Break Down Problems
Stepwise refinement is breaking down a problem into smaller tasks.
59
Stepwise Refinement Break Down Problems Example
Breaking down a check-writing program into functions like digitName, tensName, etc.
60
Variable Scope Scope of Variables Example
def main(): total = 0 # local to main for i in range(10): square = i ** 2 # local to the loop
61
Global Variables
Global variables are visible to all functions.
62
Global Variables Example
balance = 1000 def withdraw(amount): global balance balance -= amount
63
Basic Properties of Lists
Lists store a sequence of elements. Accessed using the subscript operator ([]). Lists can hold values of any type.
64
Basic Properties of Lists Example
Creating a list values = [32, 54, 67.5, 29, 35, 80, 115, 44.5, 100, 65] Accessing a list element print(values[5]) # Output: 80
65
List vs. Strings
Lists are mutable; strings are immutable. Lists can hold values of any type.
66
List vs. Strings Example
values = [2.3, 4.5, 7.2, 1.0, 12.2, 9.0, 15.2, 0.5] values[8] = 5.4 # Out-of-range error as the index can range from 0 to 7
67
List Operations Example
Appending Elements friends = [] friends.append("Harry") friends.append("Emily") friends.append("Bob") Inserting an Element friends.insert(1, "Cindy") Finding an Element if "Cindy" in friends: print("She's a friend") Removing an Element friends.pop(1)
67
List Operations
Appending, inserting, finding, removing, concatenation, equality testing, and more.
68
Common List Algorithms
Filling a list, combining list elements, linear search, etc.
69
Common List Algorithms Example
Linear Search limit = 100 pos = 0 found = False while pos < len(values) and not found: if values[pos] > limit: found = True else: pos = pos + 1
70
Creating Tables
Lists can be used to store two-dimensional data.
71
Creating Tables Example
Creating a table (2D list) table = [ [1, 2, 3], [4, 5, 6], [7, 8, 9]
72
Accessing Elements in Tables
Use two indices (row and column).
73
Accessing Elements in Tables Examples
Accessing elements in a table element = table[1][2] # Accessing row 1, column 2
74
Reading from a File
Reading data from a text file involves opening the file and accessing its content.
74
Adding Rows and Columns
Compute totals for rows and columns.
75
Adding Rows and Columns Examples
Sum of elements in each row for i in range(len(table)): row_total = sum(table[i]) Sum of elements in each column for j in range(len(table[0])): col_total = sum(table[i][j] for i in range(len(table)))
76
Reading from a File Example
Opening a file for reading infile = open("input.txt", "r") Reading a line from the file line = infile.readline()
77
Writing to a File Example
Opening a file for writing outfile = open("output.txt", "w") Writing a string to the file outfile.write("Hello, World!\n")
77
Writing to a File
Writing data to a text file involves opening the file in write mode and providing the data to be written.
78
Processing Text Input
Processing text input involves reading text from files or user input and handling it based on the program's requirements.
79
Processing Text Input Example
Reading words from a file for line in inputFile: words = line.rstrip().split() # Process each word as needed
80
Handling Input Errors
Handling input errors involves managing unexpected issues, such as incorrect file formats or missing files, during file processing.
81
Handling Input Errors Examples
try: data = readFile(filename) # Process data except IOError: print("File not found.") except ValueError: print("File contents invalid.") except RuntimeError as error: print("Error:", str(error))
82
Detecting Errors
Detecting errors involves identifying issues that can occur during runtime, such as file not found or incorrect data format.
83
Detecting Errors Examples
if amount > balance: raise ValueError("Amount exceeds balance")
84
Handling Errors
Handling errors involves dealing with exceptions using try, except, and optionally finally blocks to ensure proper error management.
85
Handling Errors Examples
try: # Code that may cause an exception except IOError: print("Error: file not found.") except ValueError as exception: print("Error:", str(exception)) finally: # Code to be executed whether an exception occurs or not
86
Set
A set is a container that stores a collection of unique values. The elements in a set are not stored in any particular order, and duplicates are not allowed.
87
Set Example
colors_set = {"red", "green", "blue"}
88
Set Operations
Operations performed on sets, such as union, intersection, and difference, follow mathematical set operations.
88
Intersection Example
intersection_set = set1.intersection(set2) # Result: {3}
89
Union Example
set1 = {1, 2, 3} set2 = {3, 4, 5} union_set = set1.union(set2) # Result: {1, 2, 3, 4, 5}
90
Difference Example
difference_set = set1.difference(set2) # Result: {1, 2}
91
Membership Test
Checking whether an element is present in a set.
92
Membership Test Example
if "red" in colors_set: print("Red is present in the set.")
93
Iterating Over a Set
Since sets are unordered, you use a loop to iterate over elements.
94
Dictionary
A dictionary is a container that stores associations between keys and values. Keys are unique, and each key has an associated value.
94
Iterating Over a Set Example
for color in colors_set: print(color)
95
Dictionary Example
contacts = {"Fred": 7235591, "Mary": 3841212, "Bob": 3841212}
96
Accessing Dictionary Values
Values in a dictionary are accessed using keys.
97
Accessing Dictionary Values Examples
print("Fred's number is", contacts["Fred"])
98
Adding/Modifying Items
You can add new items or modify existing items in a dictionary.
99
Adding/Modifying Items Example
contacts["John"] = 4578102 # Adding contacts["John"] = 2228102 # Modifying
100
Iterating Over a Dictionary
You can iterate over keys, values, or items in a dictionary.
101
Iterating Over a Dictionary Example
for key in contacts: print(key, contacts[key])
102
Dictionary of Sets
A dictionary where each key is associated with a set of values.
103
Dictionary of Sets Example
index_entries = {"example": {7, 10}, "index": {7}, "program": {7, 11}}
104
Building an Index
Using a dictionary of sets to build an index, associating terms with the pages on which they occur.
105
Building an Index Example
Using a dictionary of sets to build an index, associating terms with the pages on which they occur.
106
Object-Oriented Programming
Object-Oriented Programming (OOP) is a programming paradigm that uses objects, which are instances of classes, to design and structure code. It involves the concept of encapsulation, where data and methods that operate on the data are bundled into a single unit known as a class.
107
Object-Oriented Programming Example
class Car: def __init__(self, capacity, shape): self.capacity = capacity self.shape = shape
108
Python Classes
A class in Python is a blueprint for creating objects. It defines the properties (attributes) and behaviors (methods) that the objects created from the class will have.
109
Python Classes Example
class Dog: def __init__(self, name, age): self.name = name self.age = age
110
Testing a Class
Testing a class involves verifying that its methods perform as expected. This is often done through unit testing, where individual methods of the class are tested in isolation.
111
Testing a Class Example
Assuming a class named MyClass with a method 'add' obj = MyClass() result = obj.add(3, 4) assert result == 7, "Addition method failed"
112
Pattern for Object Methods & Data
This likely refers to the practice of organizing class methods and data to achieve a clear structure. Methods in a class typically act on the class's data, and this pattern helps maintain a logical organization.
113
Pattern for Object Methods & Data Example
class Rectangle: def __init__(self, length, width): self.length = length self.width = width def calculate_area(self): return self.length * self.width
114
Object References
Object references in Python are variables that store references (memory addresses) to objects. Multiple references can point to the same object.
115
Object References Example
obj1 = MyClass() obj2 = obj1 # Both obj1 and obj2 reference the same object
116
Python Special Methods
Special methods, also known as magic or dunder methods, are prefixed and suffixed with double underscores (e.g., __init__). They provide functionality to classes, allowing customization of object creation, comparison, etc.
117
Python Special Methods Example
class MyClass: def __init__(self, value): self.value = value def __eq__(self, other): return self.value == other.value
118
Encapsulation
Hiding the implementation details and exposing only the public interface of a class to users.
118
Class Methods
Methods defined within a class that operate on class-level attributes.
118
Instance Variables
Variables that store data unique to each instance of a class.
119
Constructors
Special methods, like __init__, that initialize instance variables when an object is created.
120
Unit Testing
Testing individual methods of a class in isolation to ensure they work as expected.
121
Class
A blueprint for creating objects, defining their behavior.
122
Class Example
class CashRegister: # class definition
123
Initialization (__init__ method)
Special method used to initialize the object's attributes when it's created.
124
Initialization (__init__ method) Example
def __init__(self, itemCount=0, totalPrice=0.0): self._itemCount = itemCount self._totalPrice = totalPrice
125
Method
A function that is associated with an object.
126
Method Example
def addItem(self, price): # method definition
127
Mutator Method
Alters the object it's called on.
128
Accessor Method Example
def getTotal(self): return self._totalPrice
129
Mutator Method Example
def addItem(self, price): self._itemCount += 1 self._totalPrice += price
130
Accessor Method
Retrieves information from the object without altering it.
131
Unit Test
Verifies that a class works correctly in isolation.
132
Unit Test Example
register1 = CashRegister() register1.addItem(1.95)
133
Expected Result
The anticipated outcome of a test program.
134
Expected Result Example
print(register1.getTotal()) # Expected: 1.95
135
Object Tracing
Visualizing object behavior using index cards with method details on the front and instance variables on the back.
136
Object Tracing Example
Index card for CashRegister object # Front: addItem, getTotal, ... # Back: _itemCount, _totalPrice, ...
137
Pattern
Common strategies for designing instance variables and methods.
138
Keeping a Total Pattern
class CashRegister: def addItem(self, price): self._itemCount += 1 self._totalPrice += price
139
Object Reference
Specifies the location of an object in memory.
140
Object Reference Example
reg1 = CashRegister()
141
Shared References
Multiple variables pointing to the same object.
142
Shared References Example
reg2 = reg1
143
None Reference
Represents no object.
144
None Reference Example
reg = None
145
Special Methods
Methods in Python with double underscores, used for operator overloading.
146
Example: __eq__: Used for defining equality between objects.
Used for defining equality between objects. def __eq__(self, other): return self._itemCount == other._itemCount and self._totalPrice == other._totalPrice
147
Special Python Methods
Defined to customize behavior when objects are used with Python built-in functions.
148
Example: __float__:
Converts an object to a floating-point number. def __float__(self): return float(self._totalPrice)
149
isinstance() Function
Checks if an object is an instance of a specified type.
150
Fractional Addition
Involves adding fractions with a common denominator or using a formula for different denominators.
151
Fractional Addition Example
def __add__(self, other): # Addition of Fraction objects
152
isinstance() Function Example
if not isinstance(numerator, int) or not isinstance(denominator, int): raise TypeError("Numerator and denominator must be integers.")
153
Price and Performance Advances
Moore's Law: The observation that the number of transistors on a microchip doubles approximately every two years, leading to improved performance. Data Storage and Network Capacity: Continual advancements in both storage and network capabilities.
154
The Network is the Thing
Power of the Network: Emphasizes the importance of network access in the realm of IT. Cloud Computing: Leveraging remote servers over the internet for data storage and processing
154
Smaller is Better
Mobility: The trend towards smaller, more portable devices.
155
Hardware Components
Power Supply: Converts AC to DC: Critical for providing suitable power to components. Motherboard: Main Circuit Board: Facilitates communication among hardware components. Central Processing Unit (CPU): Executes Instructions: Performs computations and is measured in Hertz. RAM (Random Access Memory): Main Memory: Volatile and fast, serves as a "waiting room" for instructions. GPU (Graphics Processing Unit): Dedicated Graphics Processor: Manipulates computer graphics, image processing, and video rendering. Storage: Non-volatile Storage: Persistent secondary memory, examples include HDD, SSD, optical discs, flash drives, and cloud storage. Servers: PC on Steroids: More powerful and redundant compared to personal computers.
156
Computer Data Representation
Binary to Decimal Conversion: Understanding how binary numbers represent decimal values. Text Representation: Mapping characters to binary and decimal numbers. Image, Graphics, and Video Representation: Pixel encoding, color representation, and data sizes.
157
Hardware Trends
Advances in Servers: Described as "PC on Steroids," emphasizing differences and redundancies. Evolution of Storage: From traditional HDD to SSD and cloud storage. Data Size and Significance: Illustrating the magnitude of data sizes in various contexts.
158
Operating System and Application Programs
Operating System (OS): Resource Control: Manages computer resources, deals with errors, and controls I/O. Application Programs: Native and Web Applications: Describing programs based on their platform and delivery.
158
Software Licensing and Types of Applications
Proprietary Software License: Payment for License: Closed source, limited customization, may include support. Open Source: Free and Customizable: Allows modification and redistribution, supported by the community. Types of Applications: One-of-a-kind, Horizontal, Vertical: Describing the nature and purpose of different software applications.
158
Firmware and Virtualization
Firmware: Special Software on ROM: Embedded logic in devices, changeable by IT professionals. Virtualization: Hosts Virtual Machines: One physical computer hosting multiple virtual machines, controlled by a host operating system.