Week 1 Python QC

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

1/77

encourage image

There's no tags or description

Looks like no tags are added yet.

Last updated 7:18 PM on 7/14/26
Name
Mastery
Learn
Test
Matching
Spaced
Call with Kai
Chat

No analytics yet

Send a link to your students to track their progress

78 Terms

1
New cards
What is the difference between Git and GitHub?
Git is a distributed version control tool that runs locally on your machine. GitHub is a cloud-based hosting platform for Git repositories that adds collaboration features like pull requests and code review.
2
New cards
What are the three areas of a Git workflow and what command moves files between each?
Working directory → staging area (git add) → repository (git commit). git push then syncs the local repository to a remote.
3
New cards
What does git status tell you and when should you use it?
It shows which files are untracked, modified, or staged. Use it constantly — before committing, after making changes, and whenever you're unsure what state your repo is in.
4
New cards
What does HEAD point to in Git?
HEAD points to the current commit you're working from — usually the tip of your active branch. It moves forward with each new commit.
5
New cards
What is the difference between a centralized and distributed version control system?
In a centralized VCS (like SVN), there is one central server and developers check out files from it. In a distributed VCS (like Git), every developer has a full copy of the entire repository history locally.
6
New cards

What are Python's four primitive data types and what is one key fact about each?

  • int (unbounded whole numbers),

  • float (IEEE 754 decimal, imprecise),

  • bool (subclass of int, True/False), and

  • str (immutable sequence of Unicode characters).

7
New cards
What is the difference between is and == in Python?
== compares values (content); is compares identity (same object in memory). Use == for almost everything; use is only for None, True, and False.
8
New cards
What does // do and how is it different from /?
// is floor division — it divides and rounds down to the nearest integer (e.g. 7 // 2 = 3). / always returns a float (e.g. 7 / 2 = 3.5).
9
New cards
What is the LEGB rule and in what order does Python search scopes?
Python looks up names in this order: Local → Enclosing → Global → Built-in. It stops at the first scope where it finds the name.
10
New cards
What is the difference between global and nonlocal in Python?
global declares that a variable inside a function refers to the module-level global. nonlocal refers to a variable in the nearest enclosing (but non-global) scope — used inside nested functions.
11
New cards
Why should you never use a mutable default argument like a list in a function definition?
The default object is created once when the function is defined, not each time it's called. All calls that use the default share the same object, so mutations from one call bleed into the next.
12
New cards
What does if __name__ == "__main__": do and why is it important?
It checks whether the file is being run directly (not imported). Code under this guard only executes when you run the file directly, preventing side effects when the module is imported elsewhere.
13
New cards
What is *args and what data structure does it produce inside the function?
*args collects any extra positional arguments passed to a function. Inside the function it is a tuple.
14
New cards
What does pip freeze > requirements.txt do and why would you use it?
It writes all currently installed packages and their exact versions to a file. This lets others recreate the exact same environment with pip install -r requirements.txt.
15
New cards
What are the four pillars of OOP?
Encapsulation (bundling data and methods together while hiding internal details), Inheritance (a class can acquire attributes and methods from a parent class), Polymorphism (different classes can be used interchangeably through a shared interface), Abstraction (exposing only what is necessary and hiding implementation complexity).
16
New cards
What is self and why must it be the first parameter of an instance method?
self is a reference to the specific instance the method is being called on. Python passes it automatically, but you must declare it so the method can access and modify that instance's attributes.
17
New cards
What is the difference between a class attribute and an instance attribute?
A class attribute is defined on the class itself and shared by all instances. An instance attribute is set on self (usually in __init__) and unique to each object.
18
New cards
What does @classmethod receive as its first argument and when would you use it?
It receives cls — the class itself, not an instance. Use it for factory methods or when you need access to the class but not to any specific instance.
19
New cards
What is the difference between @staticmethod and @classmethod?
A @staticmethod receives no automatic first argument — it's just a regular function namespaced inside the class. A @classmethod receives cls and can access or modify the class itself.
20
New cards
What does super().__init__() do and where must it be called?
It calls the parent class's __init__, initializing the inherited part of the object. It should be called at the beginning of the child's __init__ before setting child-specific attributes.
21
New cards
What does Python's MRO stand for and what does it determine?
Method Resolution Order — it determines the order Python searches through a class hierarchy to find a method or attribute, especially important in multiple inheritance. Use ClassName.__mro__ to inspect it.
22
New cards
What default behavior does every Python class inherit from object for ==?
By default, == behaves like is — it compares identity (same object), not value. You override __eq__ to change this behavior.
23
New cards
What is encapsulation and how does Python signal a private attribute by convention?
Encapsulation means hiding internal state and only exposing a controlled interface. Python uses a single leading underscore (_name) as a convention meaning "internal use only" — it's not enforced by the language.
24
New cards
What is the difference between __str__ and __repr__?
__str__ returns a human-readable string for end users; __repr__ returns an unambiguous string for developers (ideally one you could use to recreate the object). Always implement __repr__ — it's used as the fallback when __str__ is missing.
25
New cards

What is the key difference between a list, a tuple, and a set?

  • Lists are mutable, ordered, and allow duplicates.

  • Tuples are immutable, ordered, and allow duplicates.

  • Sets are mutable, unordered, and do not allow duplicates.

26
New cards
Why can't you use a list as a dictionary key but you can use a tuple?
Dictionary keys must be hashable, which requires immutability. Lists are mutable so they have no stable hash; tuples are immutable and hashable (as long as their contents are too).
27
New cards
What is the difference between set.remove() and set.discard()?
Both remove an element, but remove() raises a KeyError if the element doesn't exist while discard() silently does nothing.
28
New cards
What does scores[1:4] return for scores = [85, 92, 78, 95, 88]?
[92, 78, 95] — slicing is inclusive of the start index and exclusive of the end index, so you get indices 1, 2, and 3.
29
New cards
What is the danger of doing alias = original with a list versus copy = original.copy()?
alias = original makes both variables point to the same list in memory — any change made through either variable affects both. copy = original.copy() creates a new independent list, so changes to one don't affect the other. Example: alias[0] = 99 also changes original[0], but copy[0] = 99 leaves original untouched.
30
New cards
What is the time complexity of membership testing (in) for a list vs a set?
O(n) for a list — it scans every element. O(1) average for a set — it uses a hash table lookup.
31
New cards
When would you use collections.deque instead of a list and why?
When you need efficient additions or removals from both ends. deque provides O(1) appendleft() and popleft(), whereas a list's equivalent operations are O(n).
32
New cards
What is the difference between an iterable and an iterator?
An iterable is any object you can loop over (has __iter__). An iterator is an object that produces values one at a time (has both __iter__ and __next__). All iterators are iterables, but not all iterables are iterators.
33
New cards
What happens when a for loop exhausts an iterator?
The iterator raises StopIteration, which the for loop catches silently and uses as the signal to stop looping.
34
New cards
What is the difference between except Exception and a bare except:?
except Exception catches all exceptions that inherit from Exception, excluding system-level ones like KeyboardInterrupt and SystemExit. A bare except: catches absolutely everything. Always use except Exception or more specific types — never a bare except:.
35
New cards
When does the else block of a try/except run?
Only when the try block completes without raising any exception. It's the "no error occurred" branch, useful for code that should only run on success.
36
New cards
When does finally run relative to a return statement inside try?
finally always runs, even if there's a return in the try block. The return is paused, finally executes, and then the return value is sent back to the caller.
37
New cards
What does bool("False") return and why is this a common trap?
It returns True — because any non-empty string is truthy in Python, regardless of its content. The string "False" is not empty, so bool("False") is True.
38
New cards
What is the difference between filter(None, iterable) and filter(lambda x: x, iterable)?
They are functionally equivalent — both remove all falsy values from the iterable. filter(None, iterable) is the idiomatic shorthand.
39
New cards
What does functools.wraps do inside a decorator and what breaks if you omit it?
@functools.wraps(func) copies the original function's metadata (__name__, __doc__, etc.) onto the wrapper. Without it, the decorated function loses its identity — its name shows as the wrapper's name, which breaks debugging, logging, and documentation.
40
New cards
What is the difference between reference counting and the gc module's role in Python's garbage collection?
Reference counting is Python's primary memory management — when an object's reference count hits zero it's immediately freed. The gc module handles circular references (where two objects reference each other), which reference counting alone cannot detect and free.
41
New cards
Why should you use %s formatting in logging calls instead of f-strings?
With %s, string interpolation only happens if the message is actually going to be logged at that level — it's deferred. With f-strings, the string is always formatted eagerly even if the log level suppresses it, wasting CPU.
42
New cards

What are the five logging levels in order from lowest to highest severity?

  • DEBUG (detailed diagnostic info for development),

  • INFO (confirmation that things are working normally),

  • WARNING (something unexpected but not breaking),

  • ERROR (a serious failure that prevented something from completing),

  • CRITICAL (a severe error that may cause the program to crash or stop).

43
New cards

How does memory management work in Python?

Python uses reference counting as its primary mechanism — when an object's reference count hits zero it's freed immediately. The gc module handles circular references that reference counting can't catch. Memory lives on the heap for objects and the stack for function call frames.

44
New cards
Where do objects and variables get stored in Python?
Objects (lists, dicts, class instances) are stored on the heap. Variable names are references stored in the current scope's namespace. Local variables live in the function's stack frame, which is discarded when the function returns.
45
New cards
Can you insert a duplicate key in a dictionary? Can you have duplicate values?
No duplicate keys — adding a key that already exists overwrites the old value. Duplicate values are allowed — multiple keys can map to the same value.
46
New cards
When would you prefer a tuple over a list?
When the data shouldn't change (coordinates, RGB values, database row), when you need it as a dictionary key (tuples are hashable, lists aren't), or when you want to signal immutability to other developers.
47
New cards
What is the difference between a lambda function and a normal function?
A lambda is a single-expression anonymous function defined inline (e.g. lambda x: x * 2). A normal function uses def, can have multiple statements, docstrings, and a name. Use lambdas for short throwaway functions (sorting keys, filter/map); use def for anything more complex.
48
New cards

What is inheritance and why do we need it in Python?

Inheritance lets a child class acquire attributes and methods from a parent class, avoiding code duplication. You use it when classes share common behavior but need specialization — e.g. Dog and Cat both inherit from Animal. Python supports single, multiple, multilevel, hierarchical, and hybrid inheritance.

49
New cards
What is the difference between a parameter and an argument?
A parameter is the variable name defined in the function signature. An argument is the actual value passed when calling the function. Example: def greet(name) — name is the parameter. greet("Alice") — "Alice" is the argument.
50
New cards

What are some predefined exceptions in Python?

  • ValueError (right type, wrong value — e.g. int("abc")),

  • TypeError (wrong type entirely — e.g. "a" + 1),

  • KeyError (dict key not found),

  • IndexError (list index out of range),

  • AttributeError (attribute doesn't exist on the object),

  • FileNotFoundError (file path doesn't exist),

  • ZeroDivisionError (division by zero).

51
New cards

What do you know about decorators in Python?

A decorator is a function that wraps another function to add behavior before or after it runs, without modifying the original function. Written with @decorator_name above the function definition. Common uses: logging, timing, access control, caching. Use @functools.wraps inside a decorator to preserve the wrapped function's metadata.

52
New cards
How would you pull even numbers from a list?
Use a list comprehension with the modulo operator. Example: evens = [x for x in numbers if x % 2 == 0]
53
New cards
How would you pull odd numbers from a list?
Use a list comprehension with the modulo operator. Example: odds = [x for x in numbers if x % 2 != 0]
54
New cards
Given a list of numbers, how would you find the 2nd largest number?
Sort the list in descending order and grab index 1, or use sorted() with a set to remove duplicates first. Example: second_largest = sorted(set(numbers), reverse=True)[1]
55
New cards
How would you count the frequency of words in a string?
Split the string into words, then use a dictionary or collections.Counter to count each word. Example: from collections import Counter; counts = Counter("hello world hello".split()) returns Counter({'hello': 2, 'world': 1})
56
New cards
What is Pandas?
A Python library for data manipulation and analysis. It provides two main structures — Series (1D) and DataFrame (2D table) — for loading, cleaning, transforming, and analyzing structured data. Example: import pandas as pd; df = pd.read_csv("data.csv")
57
New cards
What is a DataFrame in Pandas?
A 2D labeled data structure like a spreadsheet or SQL table — rows and columns with named indices. Example: df = pd.DataFrame({"name": ["Alice", "Bob"], "age": [25, 30]})
58
New cards
How would you join two DataFrames in Pandas?
Use pd.merge() for SQL-style joins on a key column, or pd.concat() to stack DataFrames vertically or horizontally. Example: pd.merge(df1, df2, on="user_id", how="inner")
59
New cards
What is SQLAlchemy?
A Python library that provides a way to interact with relational databases using Python objects instead of raw SQL. It includes an ORM (Object Relational Mapper) so you can map Python classes to database tables. Example: querying a Users table with session.query(User).filter(User.age > 18).all()
60
New cards
What is the difference between SQLAlchemy Core and SQLAlchemy ORM?
Core uses SQL expression language — you write SQL-like expressions in Python but still think in tables and rows. ORM maps Python classes directly to database tables so you work with objects instead of rows. ORM is higher-level; Core gives more control.
61
New cards
What is a Python module?
A single .py file containing Python code — functions, classes, or variables — that can be imported and reused in other files. Example: import math gives you access to everything defined in math.py.
62
New cards
What is a package in Python?
A directory containing multiple modules and an __init__.py file that makes the directory importable. Example: import numpy imports the numpy package, which contains many modules like numpy.random and numpy.linalg.
63
New cards
What is the difference between a module and a package in Python?
A module is a single .py file. A package is a directory of modules with an __init__.py file. Example: math is a module; numpy is a package containing many modules.
64
New cards

What is the difference between a list and a tuple in Python?

Lists are mutable (you can change them after creation). Tuples are immutable (you cannot). Use a list when data will change; use a tuple when data should stay fixed. Example: coordinates = (40.7, -74.0) as a tuple signals it shouldn't change.

65
New cards
What is a dictionary in Python?
A collection of key-value pairs where each key is unique and maps to a value. Lookup by key is O(1) average. Example: user = {"name": "Alice", "age": 25}; user["name"] returns "Alice".
66
New cards
What is the difference between a dictionary and a list in Python?
A list stores ordered values accessed by integer index. A dictionary stores key-value pairs accessed by key. Use a list for ordered sequences; use a dictionary when you need to look up values by a meaningful label. Example: list[0] vs dict["name"].
67
New cards
What is a Python generator?
A function that uses yield instead of return to produce values one at a time lazily — only computing the next value when asked. This uses O(1) memory instead of building the entire result at once. Example: def count_up(n): for i in range(n): yield i
68
New cards
What is the difference between yield and return in Python?
return exits the function and sends back one value. yield pauses the function, sends back a value, and resumes from where it left off on the next call. yield is used in generators to produce a sequence lazily.
69
New cards
What is the difference between a function and a method in Python?
A function is defined with def at the module level and called by name. A method is a function defined inside a class and called on an instance using dot notation. Example: len("hello") is a function; "hello".upper() is a method.
70
New cards
What is a Python class?
A blueprint for creating objects that bundles data (attributes) and behavior (methods) together. Example: class Dog: def __init__(self, name): self.name = name creates a template; d = Dog("Rex") creates an instance.
71
New cards
What is the difference between a class and an object in Python?
A class is the blueprint — it defines the structure. An object (instance) is a concrete realization of that blueprint with actual values. Example: Dog is the class; Dog("Rex") is the object.
72
New cards
What types of inheritance does Python support?
Single (one parent), multiple (two or more parents), multilevel (grandparent → parent → child), hierarchical (one parent, multiple children), and hybrid (combination). Python uses the MRO to resolve which parent's method to call when there's ambiguity.
73
New cards
What is method overriding in Python?
When a child class defines a method with the same name as a parent class method, replacing the parent's behavior for that class. Example: class Cat(Animal): def speak(self): return "Meow" overrides Animal's speak() method.
74
New cards
What is the difference between method overriding and method overloading?
Overriding: child class redefines a parent class method — resolved at runtime. Overloading: same method name with different parameter signatures — Python doesn't support traditional overloading; you simulate it with default arguments or *args.
75
New cards
What is a Python interface?
Python has no formal interface keyword. Interfaces are simulated using abstract base classes (ABCs) from the abc module — you define abstract methods that subclasses must implement. Example: class Shape(ABC): @abstractmethod def area(self): pass forces every subclass to implement area().
76
New cards
What is the difference between an abstract class and an interface in Python?
An abstract class can have some implemented methods and some abstract ones. An interface (pure ABC) has only abstract methods — no implementation. Python doesn't enforce this distinction strictly; it's a design convention.
77
New cards
What is a metaclass in Python?
A class whose instances are classes — it controls how classes themselves are created. The default metaclass is type. You use metaclasses to customize class creation, add validation, or enforce patterns. Example: class SingletonMeta(type) can enforce that only one instance of any class using it is ever created.
78
New cards
What is the difference between a class and a metaclass in Python?
A class is a blueprint for objects. A metaclass is a blueprint for classes. Just as Dog() creates an instance of Dog, type("Dog", (object,), {}) creates the Dog class itself — type is the metaclass behind every class.