All Python Interview Questions
What are f-strings in Python?
An f-string (formatted string) is a string that starts with f and can hold variables and expressions inside curly braces { }. They were added in Python 3.6 and are the easiest way to format text.
name = "Robin"
age = 20
price = 49.5
print(f"{name} is {age} years old")
print(f"Next year: {age + 1}")
print(f"Total: {price:.2f}")
Output:
Robin is 20 years old
Next year: 21
Total: 49.50
:.2f shows the number with two digits after the decimal point. F-strings are shorter and easier to read than the older % formatting or format().
How does Python manage memory?
Python manages memory automatically. All objects live in a private heap, and Python frees them when they are no longer needed. It uses two ideas for this:
- Reference counting: every object keeps a count of how many names point to it. When the count becomes zero, the memory is freed at once.
- Garbage collector: finds groups of objects that point to each other (cycles) and are no longer used, which reference counting cannot free. It is available in the
gcmodule.
import sys
a = [1, 2, 3]
b = a
print(sys.getrefcount(a))
Output:
3
The count is 3 because of a, b and the temporary reference made while calling getrefcount(). You do not free memory yourself in Python, but you should avoid keeping big objects alive longer than needed.
What is the with statement in Python?
The with statement makes sure that setup and cleanup are done automatically, even if an error happens in between. It works with a context manager, which is an object that has __enter__() and __exit__() methods. The most common use is opening files.
with open("notes.txt", "w") as f:
f.write("Hello")
print(f.closed)
Output:
True
When the with block ends, the file is closed for you, so you do not need to call f.close(). It is also used for database connections, locks and temporary settings. See Python File Handling.
- « Previous
- 1
- 2
- 3