Ch. 1: Python Basics

0.0(0)
Studied by 0 people
call kaiCall Kai
learnLearn
examPractice Test
spaced repetitionSpaced Repetition
heart puzzleMatch
flashcardsFlashcards
GameKnowt Play
Card Sorting

1/26

encourage image

There's no tags or description

Looks like no tags are added yet.

27 Terms

1
New cards
[Python Basics] Variable (in Python)
A name that refers to an object. Python works out the type at runtime, so the same name can later refer to a different type.
```python
x = 5
print(type(x)) # → <class 'int'>
x = "five"
print(type(x)) # → <class 'str'>
```
2
New cards
[Python Basics] Python's core built-in types
int, float, bool, str, and None, plus the collections list, tuple, dict, and set.
```python
print(type(3), type(3.0), type(True)) # → <class 'int'> <class 'float'> <class 'bool'>
print(type("hi"), type(None)) # → <class 'str'> <class 'NoneType'>
```
3
New cards
[Python Basics] list
Ordered, mutable, allows duplicates, and indexed from 0. Example: `[1, 2, 3]`.
```python
nums = [1, 2, 3]
nums.append(4)
nums[0] = 10
print(nums) # → [10, 2, 3, 4]
```
4
New cards
[Python Basics] tuple
Ordered and immutable (can't be changed after creation). Example: `(1, 2)`. Because it can't change, it can be a dict key.
```python
point = (3, 4)
print(point[0]) # → 3
try:
point[0] = 5
except TypeError:
print("can't change a tuple") # → can't change a tuple
distances = {(0, 0): 0, point: 5} # tuples can be dict keys
print(distances[(3, 4)]) # → 5
```
5
New cards
[Python Basics] dict
Maps unique keys to values, e.g., `{"a": 1}`. It is a hash table, so lookup, insert, and delete are O(1) on average.
```python
ages = {"Ann": 30, "Bo": 25}
ages["Cy"] = 41
print(ages["Bo"]) # → 25
print("Ann" in ages) # → True
```
6
New cards
[Python Basics] set
An unordered collection of unique items, e.g., `{1, 2, 3}`. Membership tests (`x in s`) are O(1) on average.
```python
seen = {1, 2, 2, 3}
print(seen) # → {1, 2, 3} ← duplicates are dropped
print(2 in seen) # → True
seen.add(4)
print(len(seen)) # → 4
```
7
New cards
[Python Basics] Mutable vs. immutable
Mutable objects can change in place (list, dict, set). Immutable objects can't (int, float, str, tuple).
```python
nums = [1, 2]
nums.append(3) # the list changes in place
word = "hi"
louder = word.upper() # strings can't change, so upper() returns a new one
print(nums, word, louder) # → [1, 2, 3] hi HI
```
8
New cards
[Python Basics] How do you get the first and last items of a list?
`nums[0]` is the first item; `nums[-1]` is the last.
```python
nums = [10, 20, 30, 40]
print(nums[0], nums[-1]) # → 10 40
print(nums[-2]) # → 30
```
9
New cards
[Python Basics] Slicing: what does `nums[1:4]` return?
A NEW list with the items at indexes 1, 2, and 3. The start is included and the end is excluded. Copying k items costs O(k).
```python
nums = [10, 20, 30, 40, 50]
print(nums[1:4]) # → [20, 30, 40]
print(nums[:2]) # → [10, 20]
print(nums[::-1]) # → [50, 40, 30, 20, 10] ← a reversed copy
```
10
New cards
[Python Basics] range(): what do `range(5)` and `range(5, 0, -1)` produce?
`range(5)` → 0, 1, 2, 3, 4. `range(5, 0, -1)` → 5, 4, 3, 2, 1. The stop value is always excluded.
```python
print(list(range(5))) # → [0, 1, 2, 3, 4]
print(list(range(5, 0, -1))) # → [5, 4, 3, 2, 1]
print(list(range(0, 10, 3))) # → [0, 3, 6, 9]
```
11
New cards

[Python Basics] for loop vs. while loop

A for loop runs once per item in a sequence. A while loop repeats as long as its condition is True.

total = 0
for n in [1, 2, 3]:
    total += n
print(total)   # → 6

n = 10
steps = 0
while n > 1:
    n //= 2
    steps += 1
print(steps)   # → 3


12
New cards
[Python Basics] What are `7 / 2`, `7 // 2`, and `7 % 2`?
`7 / 2` = 3.5 (true division, always a float). `7 // 2` = 3 (floor division). `7 % 2` = 1 (remainder).
```python
print(7 / 2, 7 // 2, 7 % 2) # → 3.5 3 1
print(-7 // 2) # → -4 ← floor division rounds DOWN, not toward 0
```
13
New cards
[Python Basics] What does `2 ** 10` compute?
2 to the 10th power = 1024. `**` is the exponent operator.
14
New cards
[Python Basics] `==` vs. `is`
`==` checks whether two values are equal. `is` checks whether two names refer to the same object in memory.
```python
a = [1, 2]
b = [1, 2]
c = a
print(a == b, a is b) # → True False
print(a is c) # → True
```
15
New cards
[Python Basics] Truthiness: which values count as False?
0, 0.0, None, "" (empty string), and empty collections like [], {}, set(). So `if not nums:` checks for an empty list.
```python
nums = []
if not nums:
print("empty") # → empty
print(bool(0), bool("hi"), bool(None)) # → False True False
```
16
New cards
[Python Basics] What does a function return if it has no return statement?
None.
```python
def greet(name):
print("hi", name)

result = greet("Ann") # → hi Ann
print(result) # → None
```
17
New cards

[Python Basics] Mutable default argument pitfall

def f(items=[]) shares ONE list across every call. Use def f(items=None) and create the list inside the function.

def add_bad(item, items=[]):
    items.append(item)
    return items

print(add_bad(1))   # → [1]
print(add_bad(2))   # → [1, 2]  ← the same list was reused!

def add_good(item, items=None):
    if items is None:
        items = []
    items.append(item)
    return items

print(add_good(1))  # → [1]
print(add_good(2))  # → [2]


18
New cards
[Python Basics] List comprehension
A one-line way to build a list: `[x * x for x in nums if x > 0]` squares every positive x.
```python
nums = [-2, 1, 3]
print([x * x for x in nums if x > 0]) # → [1, 9]
print([x * 2 for x in nums]) # → [-4, 2, 6]
```
19
New cards
[Python Basics] enumerate()
Loops over index and value together: `for i, value in enumerate(nums):`.
```python
for i, name in enumerate(["Ann", "Bo"]):
print(i, name) # → 0 Ann, then 1 Bo
```
20
New cards
[Python Basics] How do you raise and catch an error?
Raise: `raise ValueError("message")`. Catch: `try: ... except ValueError: ...`.
```python
def safe_divide(a, b):
if b == 0:
raise ValueError("can't divide by zero")
return a / b

try:
safe_divide(1, 0)
except ValueError as e:
print("Error:", e) # → Error: can't divide by zero
```
21
New cards
[Python Basics] Common Python exceptions
IndexError (bad list index), KeyError (missing dict key), TypeError (wrong type, e.g., comparing objects with no `<`), ValueError (right type, bad value).
```python
try:
[1, 2][5]
except IndexError:
print("IndexError") # → IndexError
try:
{"a": 1}["b"]
except KeyError:
print("KeyError") # → KeyError
```
22
New cards
[Python Basics] dict methods you'll use most
`d.get(key, default)`, `d.items()`, `d.keys()`, `d.values()`, and `key in d`.
```python
ages = {"Ann": 30, "Bo": 25}
print(ages.get("Cy", 0)) # → 0 ← no KeyError, just the default
for name, age in ages.items():
print(name, age) # → Ann 30, then Bo 25
```
23
New cards
[Python Basics] `sorted(nums)` vs. `nums.sort()`
`sorted()` returns a NEW sorted list; `.sort()` sorts in place and returns None. Both are O(n log n) and accept `key=` and `reverse=True`.
```python
nums = [3, 1, 2]
print(sorted(nums), nums) # → [1, 2, 3] [3, 1, 2]
print(nums.sort()) # → None
print(nums) # → [1, 2, 3]
words = ["bb", "a", "ccc"]
print(sorted(words, key=len, reverse=True)) # → ['ccc', 'bb', 'a']
```
24
New cards
[Python Basics] f-string
A string with values inserted using `{}`: `f"{name} is {age}"`. `{value!r}` inserts the repr() of the value.
```python
name, age = "Ann", 30
print(f"{name} is {age}") # → Ann is 30
print(f"{name!r}") # → 'Ann'
print(f"{2 / 3:.2f}") # → 0.67
```
25
New cards
[Python Basics] Code: Write a function that counts how often each item appears in a list.
```python
def count_items(items):
counts = {}
for item in items:
counts[item] = counts.get(item, 0) + 1
return counts
```
26
New cards
[Python Basics] Code: Write a function that returns the largest number in a non-empty list without using max().
```python
def find_max(nums):
largest = nums[0]
for num in nums[1:]:
if num > largest:
largest = num
return largest
```
27
New cards
[Python Basics] Runtimes of common list operations
Index, `append`, `pop()`, `len`: O(1). `insert(0, x)`, `pop(0)`, `x in nums`, `remove(x)`: O(