Back to notes
Describe the functionality of the 'replace' string method in Python.
Press to flip
The 'replace' method returns a copy of a string with all occurrences of a specified substring replaced by another substring.
Explain the difference between 'write' and 'append' modes when opening a file in Python.
'write' mode ('w') overwrites the file if it exists, or creates a new file if it doesn't. 'append' mode ('a') adds new data to the end of the file without erasing the existing content.
Write a Python class definition for a Student that includes a method to check if a student is on the honor roll (GPA >= 3.5).
```python class Student: def __init__(self, name, major, gpa): self.name = name self.major = major self.gpa = gpa def on_honor_roll(self): return self.gpa >= 3.5 ```
Write a Python code snippet to install a package using PIP.
pip install package_name
What is an inherited class in Python, and how do you define it?
An inherited class in Python derives attributes and methods from another class. Example: ```python class DerivedClass(BaseClass): pass ```
What is the purpose of a try/except block in Python?
To handle exceptions (errors) and allow the program to continue execution without crashing.
How can you read all lines from a text file in Python and print each line?
```python employee_file = open('file.txt', 'r') for line in employee_file.readlines(): print(line) employee_file.close() ```
Why should new developers prefer Python 3.x over Python 2.x?
Python 3.x is future-proof and continues to receive updates and support, whereas Python 2.x is deprecated.
Differentiate between a tuple and a list in Python.
A list is mutable (can be changed), while a tuple is immutable (cannot be changed).
What is the purpose of the 'range' function in a Python for loop, and give an example of its use.
The 'range' function generates a sequence of numbers. Example: ```python for i in range(5): print(i) ```
How can you loop through a dictionary's keys and values in Python?
```python my_dict = {'a': 1, 'b': 2, 'c': 3} for key, value in my_dict.items(): print(key, value) ```
What are three key reasons Python is considered a beginner-friendly programming language?
Minimal syntax, interpreted nature, and versatile applications in various domains.
How do you define and invoke a function in Python that returns the cube of a number?
```python def cube(num): return num * num * num ```
Give an example of how nested loops might be used with 2D lists in Python.
```python 2d_list = [[1, 2], [3, 4], [5, 6]] for row in 2d_list: for col in row: print(col) ```
Explain the difference between the 'append' and 'insert' methods of a Python list.
'append' adds an element to the end of the list, while 'insert' adds an element at a specified index.
Previous
Next