Python Flashcards

(95 cards)

1
Q

What is the Python equivalent of null?

A

None = nothing there in python/null

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

How do you create a null-like value to a variable in Python?

A

varName = None

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

How do you print a None value in Python?

A

print(varName)
where varName=None

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

What is a tuple in Python?

A

Tuples are ordered IMMUTABLE lists defined within ()

x = (1,5,2,3)
TUPLE
Ordered=values aren’t sorted into an order and can’t be as tuples are immutable/can’t be changed or modified.

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

What is a list in Python?

A

A list [] is a mutable collection of items defined with square brackets, e.g., [1, 2, 3].
Zero-Indexed.
To access a value just varName[2] or whatever index.

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

Which Python data structure only stores unique values?

A

Sets = {} only store unique values so if you create set1 = {1,1,1}
set1= {1} as the others get ignored.

If you wrote:
a = 1
b = 1
c = 1
my_set = {a, b, c}
Same result, my_set={1} — even though you used three different variable names, they all resolve to the same value, so only one instance goes into the set.

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

If you create a Python set like {1, 2, 1}, how many elements are stored?

A

Two elements {1,2} are stored—Python sets discard duplicates before storing anything.

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

How do you check the data type of a variable in Python?
e.g. you have a var called varName

A

type(varName)

Use the type() function, e.g., type(x)

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

What does the len() function do?

A

It returns the number # of elements in a sequence like a list, string, tuple, or set.

len([1, 2, 3]) # Returns 3

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

How do you create a set with unique values?

A

A set {} is an unordered collection of unique items, created with curly braces. Duplicates are automatically removed
my_set = {1, 2, 2, 3}
print(my_set) # Output: {1, 2, 3}

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

How do you define and call a function in Python?

A

Define a function with def keyword; call it by name with parentheses and arguments (what you enter instead of the placeholders).

def add(a, b):
return a + b

result = add(2, 3) # result is 5

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

How do you write a for loop to iterate over a range?

A

Use for x in range(start, stop): to loop through numbers. for i in range (1,100):

for i in range(1, 4):
print(i) # Prints 1 2 3 each on a new line

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

How do you check if a value exists in a list or set?

A

Use the if and in keyword to test membership of a value in a list [] or set ()

if 2 in [1, 2, 3]:
print(“Found 2”)

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

What is linting in programming?

A

Linting is the automated process of checking your code for errors, stylistic issues, and potential bugs before running it.

VS Code uses syntax highlighting (not linting) powered by language grammar files and themes to color code your text (keywords, variables, strings, etc.).

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

What colors code in VS Code?

A

VS Code uses syntax highlighting powered by language grammar files and themes to color code your text (keywords, variables, strings, etc.).

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

What is Python?

A

Python is a simple, interpreted, dynamically typed, easy-to-read programming language used to build websites, automate tasks, analyze data, and more.

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

What is the difference between interpreted and compiled languages?

A

Interpreted languages (like Python) run code line by line at runtime. Compiled languages (like C++) convert code into machine language before running, making them faster but less flexible.

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

What is a class in Python?

A

A class in Python is a blueprint for creating objects that defines their data (attributes) and behavior (methods - fn declared in a class).

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

What is a method in Python?

A

A method () in Python is a function (fn) defined inside a class that operates on instances of that class, typically using self to access object data.

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

What is the purpose of the __init__ method in a Python class?

A

The __init__ method is a special constructor that initializes a new object’s attributes when it is created.

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

How do you call a method attached to an object in Python?

A

By using dot notation: objectName.methodName()

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

What does self refer to inside a method?

A

self refers to the current instance of the class on which the method is called.

self = $_ equivalent = the current object in the pipeline that’s selected.

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

What are dunder methods in Python? What does dunder stand for?

A

Dunder (__Double Under__) methods are special methods (defined in a class (template) with double underscores before and after the method names that customize how objects created with classes behave with built-in operations.

They tell Python how your object should behave when you do stuff like:

Make a new one (__init__)

Print it (__str__)

Add two objects (__add__)

Think of dunder methods as magic buttons that control how your objects act in different situations. Without them, Python wouldn’t know what to do with your objects in those cases.

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

What do dunder methods do in a Python class?

A

__Dunder__ methods change how built-in Python operations like printing, adding, or comparing work for objects created from that class.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
25
What’s the difference between a method and a function?
A function is a standalone block of code you can call anywhere. A method is just a function that belongs to an object (inside a class) and usually works with that object’s data.
26
What does “instance” mean in Python?
An instance is an individual object created from a class. It’s one product of that class/blueprint. An example or single occurrence of something.
27
What is an object in Python?
An object is a specific thing created from a class that holds data (attributes) and can do actions (methods). It’s a product/instance of a class.
28
What are the three main types of conditional statements in Python?
The 3 main conditional statements in Python are: if, elif, and else statements, used to control program flow based on conditions. if x == 7: print("Lucky number 7")
29
What are conditional statements?
They are structures like if, elif, and else that execute code blocks based on whether conditions (which often use comparison operators) are True or False.
30
What are comparison operators?
Comparison operators are symbols like ==, !=, <, >, <=, and >= that compare two values and return True or False. x = 10 print(x > 5) # True
31
What is elif?
elif is a Python keyword that means “else if.” It allows you to check multiple conditions sequentially after an initial if. x = 7 if x > 10: print("x is big") elif x == 7: print("x is seven") else: print("x is small")
32
What does else do?
else catches all other conditions not met by any previous if or elif checks. It’s the “catch-all” fallback in your conditional logic. x = 2 if x > 10: print("x is big") elif x == 7: print("x is seven") else: print("x is something else") If none of the earlier conditions are true, the else block runs.
33
Is Python case sensitive?
Yes, Python is case SENSITIVE so it treats uppercase and lowercase letters as different. None, none, and NONE are not the same. x = None print(x) # Valid x = none # Error: 'none' is not defined
34
What are identity (in memory) operators?
Identity operators are Python operators (is and is not) that check whether two variables refer to the same object IN MEMORY. x is y returns True if x and y are the same object. x is not y returns True if they are different objects.
35
What is the purpose/function of not?
not flips a True to False, or False to True. It reverses the condition so you can say “if NOT this, then do that.” not makes your code cleaner and easier to read when dealing with opposite conditions dynamically. Using not dynamically means you can invert whatever Boolean value a variable or expression currently holds at runtime, WITHOUT KNOWING or hardcoding its value before running. is_raining = get_weather_forecast() # Could be True or False dynamically if not is_raining: print("Go outside") else: print("Stay inside")
36
What is a for loop in Python?
A for loop in Python is a control structure that repeats a block of code for each item in a sequence like a list, string, tuple, or range.
37
What is a while loop in Python?
A while loop in Python is a control structure that repeats a block of code as long as a given condition is True. count = 3 while count > 0: print("Countdown:", count) count -= 1 Countdown: 3 Countdown: 2 Countdown: 1
38
What is the break statement in Python loops?
The break statement in Python loops is used to immediately exit the loop, even if the loop condition is still true or items remain in the sequence.
39
What is the continue statement in Python loops?
The continue statement in Python loops is used to skip/bypass the rest of the current loop iteration and move on to the next one. for number in range(1, 6): if number == 3: continue # skip the rest of the loop when number is 3 print(number)
40
What is the else clause in Python loops?
The else clause in Python loops is an optional block that runs after the loop finishes normally (not interrupted by break).
41
What is range() used for in for loops?
range() is used to generate a sequence of numbers for a for loop to iterate over.
42
What will the following code output? for i in range(3): print(i)
0 1 2
43
What will the following code output? x = 5 while x > 2: print(x) x -= 1
5 4 3
44
What will the following code output? for letter in "hi": print(letter)
h i
45
What will the following code output? for i in range(1, 6, 2): print(i)
1 3 5 range(1, 6, 2) means: start at 1, go up to (but not including) 6, stepping by 2 each time.
46
What will the following code output? count = 0 while count < 3: print("looping") count += 2
looping looping (count = 2 then 4 which is <3 so loop stops as condition no longer True)
47
What will the following code output? for i in range(7, 10, 3): print(i)
7 range(7, 10, 2) starts at 7 and steps/increments by 3 but stops before reaching 10, so it only includes 7.
48
What does the condition if i % 5 == 0: check in Python?
The condition if i % 5 == 0: checks if the variable i is divisible by 5 without any remainder, meaning i is a multiple of 5.
49
What is the modulo operator % in Python?
The modulo operator % in Python returns the remainder after dividing one number by another. 10 % 3 # Returns 1 because 10 divided by 3 is 3 with a remainder of 1
50
What is an object in Python?
An object is an instance of a class containing actual data and can use the class’s methods.
51
How do you define a dictionary?
Using curly braces {} with key-value pairs separated by colons. Example: my_dict = {"key1": "value1", "key2": "value2"}
52
What is a dictionary in Python?
A dictionary is a collection of key-value pairs where each key maps to a value. Keys are UNIQUE and IMMUTABLE. Dictionaries can be iterated over, just like a list. However, a dictionary, unlike a list, does not keep the order of the values stored in it.
53
How do you access a value in a dictionary?
By using the key inside square brackets: my_dict["key1"] # returns "value1"
54
How do you add or update a key-value pair to a Python dictionary? Lets say you wanted to add a key:value pair of: "key3" : "value3" to a dictionary var my_dict
my_dict["key3"] = "value3" If there already was a "key3" this same syntax would update/overwrite its value with "value3" from whatever it was before.
55
How do you remove a key-value pair from a Python dictionary?
Use del or .pop(): del my_dict["key2"] value = my_dict.pop("key1")
56
What happens if you access a non-existent dictionary {} key?
It raises a KeyError. Use .get() to avoid this and return None or a default value instead: my_dict.get("missing_key", "default")
57
How do you iterate over key-value pairs in a dictionary?
Use .items() method to iterate over key-value pairs in a dictionary {}: for key, value in my_dict.items(): print(key, value)
58
What is pop() in a dictionary?
pop(key) removes the key-value pair for the specified key and returns the value. Raises KeyError if key not found unless a default is provided. value = my_dict.pop("key1") # removes "key1" and returns its value
59
What is del in a dictionary?
del my_dict[key] removes the key-value pair for the specified key but does not return the value. Raises KeyError if key not found. del my_dict["key1"] # removes "key1" from the dictionary
60
When to use pop() vs del when removing from dictionaries?
Use pop() if you need the removed value. Use del if you just want to remove the key without caring about the value.
61
What is a module in Python?
A module is a single Python file (.py) that contains variables, functions, and classes you can reuse.
62
How do you import a module?
Using the import statement. Example: import math or import math as mth Then can call its function via mth.sqrt() Etc.
63
What is a package in Python?
A package is a folder containing multiple modules and an __init__.py file to group related modules together. __init__.py marks a directory as a Python package and can run initialization code for the package.
64
How do you import specific functions or classes from a module?
from module_name import function_name
65
How do you import from a package?
from package_name import module_name
66
What is the input() function in Python?
input() reads a line of text inputted by the user and returns it as a string.
67
What is a generator in Python?
A generator is a special type of function that YIELD items one at a time, creating an iterable sequence without storing the entire sequence in memory and pausing the function between calls to save memory. You then call each further iteration of the function with next() that continues from where the last yield left off. def ticket_machine(): yield 1 yield 2 yield 3 When you run this function, nothing happens yet. You have to call next() to get each value. gen = ticket_machine() print(next(gen)) # 1 print(next(gen)) # 2 print(next(gen)) # 3
68
What does a for loop do in Python? Explain what it’s used for, and give a basic example.
For loops in Python are used to iterate over a SEQUENCE (like a list, string, or range) and run a block of code for each item in that sequence. for i in range(5): print(i)
69
What is the difference between ordered and unordered data types in Python?
Ordered and unordered data types in Python differ in how they store and access elements: Ordered data types (like list [], tuple (), str "", and dict {} in Python 3.7+) maintain the sequence of elements. You can access items by index or rely on their order. Example: my_list = [10, 20, 30] → my_list[0] is 10 Unordered data types (like set and dict pre-3.7 {}) do not guarantee any order. You can't rely on the position of elements. Example: my_set = {3, 1, 2} → order is unpredictable
70
What is a list comprehension in Python?
A list comprehension is a faster way to create lists by applying an expression to each item in an iterable, optionally filtering items. squares = [x**2 for x in range(5)] # squares = [0, 1, 4, 9, 16] x squared = 0 squared = 0. 1 squared = 1 2 squared = 4 etc
71
What is inheritance in Python classes? Explain what inheritance means.
Inheritance means a class (child/subclass) can reuse and extend the properties and methods of another class (parent/superclass). It lets you build on existing code without rewriting it. Inheritance lets you override or add new behavior while keeping the base functionality. class Animal: def speak(self): print("Animal speaks") class Dog(Animal): def speak(self): print("Woof!") dog = Dog() dog.speak() # Outputs: Woof!
72
What is meant by OOP?
OOP (Object-Oriented Programming) is about organizing your code around objects — things that combine data (attributes) and methods (functions attached to objects).
73
What is encapsulation?
Encapsulation is the practice of bundling data and methods inside a class and hiding internal details from outside code.
74
What is inheritance?
Inheritance is when a subclass automatically gains attributes and methods from its parent class, enabling code reuse.
75
What is polymorphism?
Same method name (e.g. speak()), different behavior depending on the object calling it (e.g. cat.speak() returns "meow" but dog.speak() returns "woof"). Polymorphism is when methods with the same name behave differently depending on the object calling them. Using the same method name on different objects, and each object runs its own version of that method.
76
What is abstraction?
Abstraction is exposing only essential features to outside code (code outside the classes scope) while hiding complex implementation details inside the class. class Dog: def speak(self): return "Woof!" class Cat: def speak(self): return "Meow!" for animal in [Dog(), Cat()]: print(animal.speak()) # Each object runs its own version of speak()
77
What is self in Python?
self is a reference to the current object (instance) of a class. It lets you access and modify that object's attributes and methods from within the class. Think of self as the word "this object". Used inside a class. Refers to the current object the method is acting on. class Car: def __init__(self, color): self.color = color # 'self.color' is the object's own color
78
What is super()?
super() is a built-in Python function that allows a subclass to call methods (usually __init__) from its parent class, enabling reuse of the parent’s code and proper initialization of inherited attributes. This means that you can use the parent classes' methods() from within a subclass/child-class without rewriting that code in each child-class/subclass.
79
What is pass in Python?
Pass is a placeholder/skip statement in Python that does nothing when executed. It is used to keep the code syntactically correct when a statement is required but no action is needed or the code will be added later.
80
What is enumerate()?
enumerate() is a built-in function that returns each item in a list along with its index, often used in for loops when you need both the item and its position. habits = ["Read", "Code", "Exercise"] for i, habit in enumerate(habits): print(f"{i+1}. {habit}")
81
What is string interpolation?
String interpolation is the process of inserting values (variables, expressions) directly into a string, so the string dynamically includes those values. String interpolation name = "Alex" print("Hello, {}".format(name)) String interpolation has been superseced/improved by f-strings in newer Python versions!
82
What are f-strings?
f-strings are formatted string literals that allow embedding Python expressions inside strings using {} for easy and readable string interpolation. name = "Alice" age = 30 print(f"My name is {name} and I am {age} years old.") >>My name is Alice and I am 30 years old. The expressions in {} are evaluated and converted to strings and inserted into the output.
83
How do you show an expression literally inside an f-string along with its evaluated result? Example: f"The expression {{2 + 2}} = {2 + 2}" outputs The expression {2 + 2} = 4.
Use double braces {{ }} around the expression to show it literally, and single braces {} to evaluate it. Example: f"The expression {{2 + 2}} = {2 + 2}" outputs The expression {2 + 2} = 4.
84
What are instance attributes?
Instance attributes are variables that belong to a specific object (instance) of a class. Each object can have different values for these attributes. class Car: def __init__(self, make, model): self.make = make # instance attribute self.model = model # instance attribute car1 = Car("Toyota", "Corolla") car2 = Car("Honda", "Civic") print(car1.make) # Toyota = differing instance attribute to the car 2 object/instance print(car2.make) # Honda
85
What are class attributes?
Class attributes are (constant) variables that are shared (the same) across all instances of a class. They are defined directly in the class, not inside the __init__ method. Use class attributes when: The value should be the same for all instances. You're storing shared data or constants. class Dog: species = "Canis familiaris" # class attribute def __init__(self, name): self.name = name # instance attribute dog1 = Dog("Buddy") dog2 = Dog("Max") print(dog1.species) # Canis familiaris print(dog2.species) # Canis familiaris
86
What is a Python decorator?
A Python decorator is a function that takes another function (or method) as input and returns a new function that adds some kind of functionality or behavior before or after the original function runs, without modifying the original function’s code. def my_decoratorFunction(func): def wrapper(): print("Before the function runs") func() print("After the function runs") return wrapper @my_decoratorFunction #applies the pre-defined decorator function/wrapper to say_hello() def say_hello(): print("Hello!") say_hello() Inbuilt decorator examples : @classmethod wraps a method so it gets the class (cls) instead of the instance (self). @staticmethod wraps a method to remove the automatic first argument altogether. @property wraps a method so you can access it like an attribute.
87
What is a staticmethod?
A staticmethod is a method inside a class that doesn’t receive self (instance) or cls (class) as its first argument. It behaves like a regular function but lives inside the class namespace. Their behaviour DOESN'T change based on object or class data. It's an inbuilt decorator function. @staticmethod class MathUtils: @staticmethod def add(a, b): return a + b print(MathUtils.add(5, 3)) # Output: 8
88
Inbuilt decorator functions (@decFuncName)
Instance methods depend on the particular object (instance) — they can access or modify the object’s attributes. Class methods depend on the class as a whole — they can access or modify class-level data. Static methods don’t depend on either; they’re just regular functions scoped inside the class for organization.
89
What is cls?
cls is the conventional name for the first parameter of a class method in Python. It refers to the class itself, not an instance of the class. cls=the current class object that the method belongs to.
90
Given the dictionary: fruit_prices = {'apple': 2, 'banana': 1, 'cherry': 3} Write a loop that prints: The price of is
for fruit, price in fruit_prices.items(): print(f"The price of {fruit} is {price}")
91
What are f-strings in Python?
F-strings (formatted string literals) let you embed Python expressions inside strings using curly braces {}. They start with an f or F before the opening quote. name = "Alice" age = 30 print(f"{name} is {age} years old.") # Output: Alice is 30 years old.
92
What happens if you assign a value to a key that already exists in a dictionary? A) A KeyError is raised B) A new duplicate key is added C) The existing value is overwritten D) The assignment is ignored
C) The existing value is overwritten
93
What is the result of this code? my_dict = {"a": 1, "b": 2} my_dict.update({"c": 3, "a": 99}) print(my_dict)
{'a': 99, 'b': 2, 'c': 3}
94
Which method merges another dictionary into the current one, updating existing keys and adding new ones? A) append() B) extend() C) update() D) merge()
C) update() update() merges another dictionary into the current one. It overwrites existing keys and adds new ones.
95
What are f-strings in Python?
f-strings are a way to create strings with embedded Python expressions using {} — introduced in Python 3.6. They’re called “f-strings” because you start the string with an f"". name = "Alex" age = 25 print(f"My name is {name} and I'm {age} years old.") //My name is Alex and I'm 25 years old.