Best Practices Flashcards

1
Q

Avoid unnecessary use of global variables

A

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)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Handle exceptions

A

try:
result = 10 / 0 # Division by zero
print(result)
except ZeroDivisionError:
print(“Error: Division by zero!”)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Concatenate with join

A

my_list = [‘apple’, ‘banana’, ‘cherry’]
result = “”
for fruit in my_list:
result += fruit # Incorrect string concatenation
print(result)

result = ““.join(my_list)
print(result)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Use list comprehensions

A

Traditional loop

squares = []
for i in range(10):
squares.append(i ** 2)
print(squares)

squares = [i ** 2 for i in range(10)]
print(squares)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Use context managers

A

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)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

Avoid using eval

A

x = 10
eval(‘x + 5’) # Avoid using eval()

x = 10
result = x + 5
print(result)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

Consistent indentation using spaces

A

def my_function():
if True:
print(“Hello, world!”) # Incorrect indentation due to mixing tabs and spaces

my_function()

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

Use descriptive names

A

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)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly