<style>
.markdown-body h1:first-of-type {
margin-top: 24px;
}
.markdown-body h1 {
margin-top: 64px;
}
.markdown-body h1 + h2 {
margin-top: 32px;
}
.markdown-body h2 {
margin-top: 48px;
}
.markdown-body h2.topics {
font-size: 1.8em;
border-bottom: none;
}
.markdown-body h3 {
color: cornflowerblue;
}
.markdown-body h4 {
color: cornflowerblue;
}
.markdown-body p strong {
}
.exercise {
font-size: 150%;
font-weight: bold;
color: rgb(227,112,183);
}
.note {
color: red;
}
ul ul ::marker {
content: '- ';
}
</style>
# ACIT 1515 - Final Review
<h2 class="topics">Topics</h2>
- [The Building Blocks of Python](#Review-The-Building-Blocks-of-Python)
- [Problem Solving: Strategies for Writing Programs](Problem-Solving-Strategies-for-Writing-Programs)
### The Building Blocks of Python
#### Variables and Data Types
```python=
name = 'Ed' # string - any value between quotation marks, immutable
age = 12 # integer
mark = 85.5 # float
courses = [] # empty list - mutable, ordered
x = (1, 2) # tuple - immutable
y = set() # empty set - mutable, unordered, unique values only
z = {} # empty dictionary, contains key/value pairs
dog = { # dictionary
"name": "Charlie",
"age": 12
}
# Get the data type of a value or variable
print(type(10)) # <class 'int'>
print(type(dog)) # <class 'dict'>
```
#### Basic Operators
```
Arithmetic
+, -, *, /, %, **
Assignment
=
Comparison
==, !=, >, <, >=, <=
Logical
and, or, not
```
#### Loops
```python=
# For loop with range, use when a number or position is required
for i in range(10):
print(i)
for i in range(len(name)):
print(i, name[i])
# For loop with sequence, use when a value is required and position is not
for val in x:
print(val) # 1, 2
for val in name:
print(val) # 'E', 'd'
# For loop with dictionary
for k in d.keys():
print(k) # prints keys
for v in d.values():
print(v) # prints values
for k, v in d.items():
print(k, v) # prints keys and values
# While loop
while True:
# infinite loop until
break
while value > 0:
print(value)
value -= 1
```
#### Conditional statements, in operator
```python=
# Comparison
if value > 10:
print('greater than ten')
# Testing boolean value
if isWeekend:
print('Relax')
# Testing multiple conditions using and/or
if isWeekend and tired:
print('Relax')
if isWeekday or not tired:
print('Work')
# Testing whether value is in a sequence
if 5 in numbers:
print('The list contains the number 5')
# Testing whether value is a set
if 5 in number_set:
print('The set contains the number 5')
# Testing whether key exists in dictionary
if name in student:
print('Student contains the key "name"')
```
#### Functions
```python=
# Declare a function with no arguments
def f():
print('Inside the function')
# Calling/running/executing/invoking the function
f()
# Declare a function with parameters:
def g(p, q):
print(p, q)
# Calling function and passing arguments:
g(10, 20)
# Define default arguments for function parameters
def h(a, b = 20):
print(a + b)
# Calling function with default parameter arguments
h(10, 30) # prints 40, a = 10, b = 30
h(10) # prints 30, a = 10, b = 20
# Ending function with the return keyword
def j(a, b):
if type(a) != type(b):
return
print(a + b)
# Returning a value from a function using the return keyword
def k(a, b)
if type(a) != type(b):
return
return a + b
# Using the value returned from a function
result = k(10, 20)
print(result)
```
#### File operations
```python=
# Opening a file for reading
with open('test.txt', 'r') as file:
# ...
# Opening a file for writing
with open('test.txt', 'w') as file:
# ...
# Writing dictionaries/lists to JSON
with open('test.json', 'w') as file:
json.dump(data, file)
# Reading objects/lists from JSON
with open('test.json', 'r') as file:
data = json.load(file)
```
#### Exceptions
```python=
# Catch any runtime error
try:
# code that may throw an exception
except:
# handle the error and prevent the crash
# Catch any runtime error and print the interpreter's error message
try:
# code that may throw an exception
except Exception as e:
print(e) # prevent crash, print error message
# Catching specific error types
try:
# code that may throw an exception
except ValueError:
print('ValueError exception occurred')
except (FileNotFoundError, JSONDecodeError):
print('Valid data not found')
except KeyError as e:
print('KeyError exception:', e)
```
### Problem Solving: Strategies for Writing Programs
When presented with a new programming challenge:
* **Anticipate**: Take time before coding to try and define the problem for yourself, breaking it down into manageable pieces whenever possible. Ask yourself:
* What parts are familiar?
* What are the steps necessary to start and solve the problem?
* What are the inputs (user input? files? network request?) and outputs
* Once you think you have the basic idea in mind, challenge your assumptions - does your step-by-step plan cover all the edge cases and errors that may occur?
* **Translate**: Translate your ideas into data structures and programming constructs
* What variables need to be created?
* What data types should be used to represent information? Lists, sets, dictionaries?
* Are functions, loops, or conditional statements required?
* **Iterate**: Write code, small pieces at a time, testing and debugging often. As you proceed through the program you will naturally encounter problems that you did not anticipate. When that happens, don't be afraid to go back to the first step and start the process again.