Best Practices Flashcards
Avoid unnecessary use of global variables
x = 10
def increment():
global x # Unnecessary use of global variable
x += 1
print(x)
increment()
def increment(x):
return x + 1
x = 10
x = increment(x)
print(x)
Handle exceptions
try:
result = 10 / 0 # Division by zero
print(result)
except ZeroDivisionError:
print(“Error: Division by zero!”)
Concatenate with join
my_list = [‘apple’, ‘banana’, ‘cherry’]
result = “”
for fruit in my_list:
result += fruit # Incorrect string concatenation
print(result)
result = ““.join(my_list)
print(result)
Use list comprehensions
Traditional loop
squares = []
for i in range(10):
squares.append(i ** 2)
print(squares)
squares = [i ** 2 for i in range(10)]
print(squares)
Use context managers
file = open(“example.txt”, “r”) # File handle not closed
data = file.read()
print(data)
file.close()
with open(“example.txt”, “r”) as file:
data = file.read()
print(data)
Avoid using eval
x = 10
eval(‘x + 5’) # Avoid using eval()
x = 10
result = x + 5
print(result)
Consistent indentation using spaces
def my_function():
if True:
print(“Hello, world!”) # Incorrect indentation due to mixing tabs and spaces
my_function()
Use descriptive names
Cryptic variable names
x = 10
y = 20
z = x + y
print(z)
total_sum = 10
bonus_points = 20
final_score = total_sum + bonus_points
print(final_score)