Python Notes for Interview
4 min readJun 22, 2023
- Basic Syntax:
# Comment
variable = value # Variable assignment
print("Hello, World!") # Print statement
2. Data Types:
string = "Hello" # String
integer = 42 # Integer
float_number = 3.14 # Float
boolean = True # Boolean
list = [1, 2, 3] # List
tuple = (1, 2, 3) # Tuple
dictionary = {"key": "value"} # Dictionary
3. Control Flow:
if condition:
# Code to execute if condition is true
elif condition2:
# Code to execute if condition2 is true
else:
# Code to execute if all conditions are false
for item in iterable:
# Code to repeat for each item in iterable
while condition:
# Code to execute while condition is true
try:
# Code to try executing
except ExceptionType:
# Code to handle exceptions of type ExceptionType
finally:
# Code to execute regardless of exceptions
4. Functions:
def function_name(parameter1, parameter2):
# Code block
return result # Optional return statement
result = function_name(argument1, argument2) # Function call
5. Input and Output:
input_value = input("Enter a value: ") # User input
file = open("filename.txt", "r") # Open file for reading
content = file.read() # Read file content
file.close() # Close file
file = open("filename.txt", "w") # Open file for writing
file.write("Hello, World!") # Write to file
file.close() # Close file
6. Modules and Libraries:
import module_name # Import a module
from module_name import function_name # Import a specific function
import module_name as alias # Import with an alias
import random
random_number = random.randint(1, 10) # Generate a random number
7. String Manipulation:
my_string = "Hello, World!"
length = len(my_string) # Length of a string
uppercase = my_string.upper() # Convert to uppercase
lowercase = my_string.lower() # Convert to lowercase
substring = my_string[7:12] # Extract substring
split_list = my_string.split(", ") # Split string into a list
8. List Manipulation:
my_list = [1, 2, 3, 4, 5]
length = len(my_list) # Length of a list
item = my_list[2] # Access element by index
sliced_list = my_list[1:4] # Extract a sublist
my_list.append(6) # Add an element to the end
my_list.remove(3) # Remove a specific element
9. Dictionary Manipulation:
my_dict = {"name": "John", "age": 30, "city": "New York"}
keys = my_dict.keys() # Get dictionary keys
values = my_dict.values() # Get dictionary values
item = my_dict["name"] # Access value by key
my_dict["occupation"] = "Engineer" # Add a new key-value pair
del my_dict["city"] # Remove a key-value pair
10. File Handling:
with open("filename.txt", "r") as file:
content = file.read() # Read file content
with open("filename.txt", "w") as file:
file.write("Hello, World!") # Write to file
11. Error Handling:
try:
# Code that may raise an exception
except ValueError as ve:
# Code to handle ValueErrors
except FileNotFoundError:
# Code to handle FileNotFoundError
else:
# Code to execute if no exceptions are raised
finally:
# Code to execute regardless of exceptions
12. Commonly Used Functions:
range(start, stop, step) # Generate a sequence of numbers
len(sequence) # Get the length of a sequence
type(object) # Get the type of an object
sum(iterable) # Calculate the sum of elements in an iterable
sorted(iterable) # Sort elements in an iterable
13. Object-Oriented Programming (OOP):
class MyClass:
def __init__(self, attribute):
self.attribute = attribute
def method(self):
# Code block
my_object = MyClass("value") # Create an instance of MyClass
my_object.method() # Call a method of the object
14. Lambda Functions:
addition = lambda x, y: x + y # Create a lambda function
result = addition(3, 4) # Call the lambda function
15. Sets:
my_set = {1, 2, 3, 4, 5}
my_set.add(6) # Add an element to the set
my_set.remove(3) # Remove an element from the set
union_set = my_set.union({7, 8, 9}) # Perform set union
intersection_set = my_set.intersection({4, 5, 6}) # Perform set intersection
16. List Comprehensions:
numbers = [1, 2, 3, 4, 5]
squared_numbers = [x ** 2 for x in numbers] # List comprehension
filtered_numbers = [x for x in numbers if x % 2 == 0] # List comprehension with condition
17. DateTime:
from datetime import datetime
current_time = datetime.now() # Get current date and time
formatted_time = current_time.strftime("%Y-%m-%d %H:%M:%S") # Format datetime as a string
18. Math Functions:
import math
square_root = math.sqrt(25) # Calculate square root
rounded_number = round(3.7) # Round a number
absolute_value = abs(-5) # Calculate absolute value
19. Regular Expressions:
import re
pattern = r"\d+" # Regular expression pattern
matches = re.findall(pattern, "There are 123 apples") # Find all matches in a string
20. Virtual Environments (venv):
# Set up a virtual environment
python3 -m venv myenv
# Activate the virtual environment
source myenv/bin/activate
# Install packages within the virtual environment
pip install package_name
# Deactivate the virtual environment
deactivate