# CSCI 111 Midterm review
## 1. Basic:
### 1.1. Print function
By default, `print` function in Python will end with a newline (`\n`).
```python=1
print("Hello World") # -> "Hello World\n"
```
However, you can custom the end by using `end=`.
```python=1
print("Hello World", end="@") # -> "Hello World@"
print("Hello World", end="") # -> "Hello World" (but end without a newline)
```
You can also format your print
```python=1
candy = 5
print(f"I have {candy} candies.") # -> "I have 5 candies."
pi = 3.141592653589793
print(f'{pi:.4f}') # 3.1416
```
### 1.2. Declare variables and type:
```python=1
my_number = 1 # int
my_float = -5.6 # float
my_text = "Hello world" # string
my_number = float(my_number) # -> 1.0
my_float = int(my_float) # -> -5
my_text = int(my_text) # -> Error
my_number = str(my_number) # -> "1.0"
input_num = int(input())
input_float = float(input())
input_str = str(input())
```
## 2. Mathematics
### 2.1. Arithmetic operators
| Arithmetic operator | Description |
| -------- | -------- |
| + | The addition operator is +, as in x + y |
| - | The subtraction operator is -, as in x - y. Also, the - operator is for negation, as in -x + y, or x + -y |
| * | The multiplication operator is *, as in x * y |
| / | The division operator is /, as in x / y. |
| ** | The exponent operator is **, as in x ** y (x to the power of y) |
| // | The floor division operator is //, as in x // y. |
### 2.2. Precedence rules
| Operator/Convention | Description | Explanation |
| -------- | -------- | -------- |
| () | Items within parentheses are evaluated first | In 2 * (x + 1), the x + 1 is evaluated first, with the result then multiplied by 2 |
| exponent ** | ** used for exponent is next | In x**y * 3, x to the power of y is computed first, with the results then multiplied by 3 |
| unary - | - used for negation (unary minus) is next | In 2 * -x, the -x is computed first, with the result then multiplied by 2 |
| * / % | Next to be evaluated are *, /, and %, having equal precedence | % is a division but return only the remainder |
| + - | Finally come + and - with equal precedence | In y = 3 + 2 * x, the 2 * x is evaluated first, with the result then added to 3, because * has higher precedence than +. Spacing doesn't matter: y = 3+2 * x would still evaluate 2 * x first |
| left-to-right | If more than one operator of equal precedence could be evaluated, evaluation occurs left to right. Note: The ** operator is evaluated from right-to-left. | In y = x * 2 / 3, the x * 2 is first evaluated, with the result then divided by 3 |
```python=1
x = 5
y = 4
print(x + y) # -> 9
print(x - y) # -> 1
print(x * y) # -> 20
print(x / y) # -> 1.25
print(x // y) # -> 1
print(x % y) # -> 1
print(x ** y) # -> 625
```
### 2.3. Math module
## 3. Types & basic data structures
### 3.1. String
String is a sequence of character. In Python, string is **immutable** (cannot be changed).
```python=1
text = "Lorem ipsum dolor sit amet"
# Length
print(len(text)) # -> 26
# Indexing & sequencing
print(text[0], text[10]) # -> "L m"
print(text[26]) # -> Error
print(text[15:24]) # -> "or sit am"
# Concatenation
add_text = ", consectetur"
full_text = text + add_text
print(full_text) # -> "Lorem ipsum dolor sit amet, consectetur"
```
##### Common errors:
- String does not support item assignment
```python=1
text = "Hello World"
text[5] = "x" # -> Error
```
- Concatenate different types with str
```python=1
text = "Hello World"
a = 5
print(text + a) # -> Error
```
### 3.2. List
List is a very common data structure in Python. List is **mutable** and **ordered**.
```python=1
# Creating
arr = [1, 5, 2, 10, 9, 8, 6, 4, 3]
# Length
print(len(arr)) # -> 9
# Min, max & sum
print(min(arr)) # -> 1
print(max(arr)) # -> 10
print(sum(arr)) # -> 48
# Indexing & sequencing
print(arr[5]) # -> 8
print(arr[2:5]) # -> [2, 10, 9]
# Updating
arr[0] = 0
print(arr) # -> [0, 5, 2, 10, 9, 8, 6, 4, 3]
# Adding & removing
arr.append(16) # Add to the end
print(arr) # -> [0, 5, 2, 10, 9, 8, 6, 4, 3, 16]
arr.insert(1, 10) # Insert 10 at position 1
print(arr) # -> [0, 10, 5, 2, 10, 9, 8, 6, 4, 3, 16]
arr.pop(1) # Remove at position 1
print(arr) # -> [0, 5, 2, 10, 9, 8, 6, 4, 3, 16]
arr.remove(16) # Remove value 16
print(arr) # -> [0, 5, 2, 10, 9, 8, 6, 4, 3]
# Concatenation
arr1 = [5, 3, 8]
new_arr = arr + arr1
print(new_arr) # -> [0, 5, 2, 10, 9, 8, 6, 4, 3, 5, 3, 8]
# Additional methods
arr.index(10) # Get index of first occurence of a value -> 3
new_arr.count(8) # Count occurence -> 2
```
### 3.3. Tuple
Tuple is another type of data structure in Python, very useful when one needs to create a fixed variable. Tuple is **immutable** and **ordered**.
```python=1
from collections import namedtuple
# Creating
tup = (7749, 4953, 7084)
# Named tuple
Car = namedtuple('Car', ['name', 'color', 'price'])
honda_civic = Car('civic', 'red', '30000')
# Indexing & sequencing
print(tup[0]) # -> 7749
print(tup[1:3]) # -> (4953, 7084)
```
### 3.4. Set
Set is **unordered** and **unindexed** data structure. Set is **unchangable** but it can remove/update items.
```python=1
# Creating
characters = ["a", "b", "c", "d", "a", "d", "e"]
char_set = set(characters)
print(char_set) # -> {'b', 'a', 'd', 'c', 'e'}
# Length
print(len(char_set)) # -> 5
# Modifying
char_set.add("x")
print(char_set) # -> {'b', 'x', 'a', 'd', 'c', 'e'}
char_set.add("e")
print(char_set) # -> {'b', 'x', 'a', 'd', 'c', 'e'}
char_set.remove("e")
print(char_set) # -> {'b', 'x', 'a', 'd', 'c'}
# char_set.remove("m") # -> Error
char_set.pop() # -> Remove a RANDOM element in set
char_set.clear() # -> Clear the set
print(char_set) # -> set()
```
### 3.5. Dictionary
A dictionary is a data structure represents associative relationship using **key-value** relationship. There cannot be same key in dictionary.
```python=1
# Creating
players = {
"Messi": 10,
"Ronaldo": 7
}
print(players) # -> {'Messi': 10, 'Ronaldo': 7}
# Accessing
print(players["Messi"]) # -> 10
# Adding
players["Benzema"] = 9
print(players) # -> {'Messi': 10, 'Ronaldo': 7, 'Benzema': 9}
# Modifying
players["Messi"] = 21
print(players) # -> {'Messi': 21, 'Ronaldo': 7, 'Benzema': 9}
# Deleting
del players["Ronaldo"]
print(players) # -> {'Messi': 21, 'Benzema': 9}
```
## 4. If-else statement
Remember to utilize nested if-else if needed.
## 5. Loop
There are 2 types of loop: `while` and `for`. Typically:
- Use `while` when you do not have a range to run, but you have a condition to stop the loop.
- Use `for` when you have a range to check.
### 5.1. While loop
```python=1
while True:
if ...:
# TODO
elif:
# TODO
else:
break
```
### 5.2. For loop
```python=1
arr = [1, 5, 6, 9, 10, 9]
for el in arr:
print(el) # -> 1, 5, 6, 9, 10, 9
for i in range(len(arr)):
print(i) # -> 0, 1, 2, 3, 4, 5
print(arr[i]) # -> 1, 5, 6, 9, 10, 9
for i, el in enumerate(arr):
print(i) # -> 0, 1, 2, 3, 4, 5
print(el) # -> 1, 5, 6, 9, 10, 9
```
## 6. Function
## 7. Common mistakes & tips
- Indexing in Python starts at **0** and ends at **len(var) - 1**.
- To get the last index, use `-1`
```python=1
text = "Hello World!"
print(text[-1]) # -> "!"
```
- Reversing for loop: using `range`. `range` will take in 3 parameters (`start`, `stop`, `step`), where `stop` is required and the other two are optional. Elements will be indexed as `[start, stop)` aka from `start` to `stop - 1` .
```python=1
arr = [1, 5, 6, 9, 10, 9]
for i in range(len(arr) - 1, -1, -1):
print(arr[i]) # -> 9, 10, 9, 6, 5, 1
```
- When using logical keywords, remember to them around parentheses
```python=1
if (a > b or c > d) and (a > c or b > d):
# TODO:
```
- Be careful when using multiple consecutive `if` statements. The program will try EVERY possible `if` statement. Use `if` with `elif` if possible.
- When reading a logical-based problem, write down what you think and work around that, if it does not work, then try the negation of it. For example, an user wants to end the program if they enter "E" or "e" or "exit" or "Exit":
```python=1
key = input()
# This one will NOT work!
while key != "E" or key != "e" or key != "exit" or key != "Exit":
# TODO
key = input()
# This one will work!
while True:
if key == "E" or key == "e" or key == "exit" or key == "Exit":
break
else:
# TODO
key = input()
```
- Instead of writing `x = x + 1`, you can write `x += 1`. This applies to every arithmetic operator.
- Remember to read through history part and write some of them down in the cheatsheet!