Python Flashcards
What are the different data types in Python?
Python has several built-in data types including int, float, str, list, tuple, dict, set, and bool
How do you create a list, tuple, or dictionary in Python?
List: my_list = [1, 2, 3]
Tuple: my_tuple = (1, 2, 3)
Dictionary: my_dict = {‘key1’: ‘value1’, ‘key2’: ‘value2’}
What is the difference between mutable and immutable data types?
Mutable: Can be changed after creation (e.g., list, dict, set).
Immutable: Cannot be changed after creation (e.g., int, float, str, tuple).
What types of loops are there?
For loops & while loops
How do you handle conditional statements?
Use if, elif, and else to execute code based on conditions.
How do you define a function in Python?
Use the def keyword:
def my_function(parameters):
# Function body
return result
What is the difference between a function and a method?
Function: A block of reusable code defined using def.
Method: A function that is associated with an object (called using object.method()).
How do you import a module in Python?
Use import module_name or from module_name import specific_function.
How do you handle exceptions in Python?
Use try and except blocks:
Can you give an example of a try-except block?
try:
result = 10 / 0
except ZeroDivisionError:
print(“Cannot divide by zero!”)
How do you read from and write to a file in Python?
Use the open() function with modes r (read) or w (write):
with open(‘file.txt’, ‘r’) as file:
contents = file.read()
What are some common methods for handling file operations?
read(), readline(), write(), and close().
How do you use a third-party library in your script?
Install with pip install library_name and import with import library_name.
What tools or environments do you use for developing Python scripts?
Common tools include IDEs like PyCharm, VS Code, and Jupyter Notebook.
What is a class in Python, and how do you create one?
A class is a blueprint for creating objects, defined using the class keyword:
class MyClass:
def __init__(self, attribute):
self.attribute = attribute