22
loading...
This website collects cookies to deliver better user experience
open
and close
instead of with
==
and is
the wrong wayimport *
f = open("stocks.txt", "r")
data = f.read()
f.close() # NOTE: Always remember to close!
with
statement) in Python while dealing with file operations. Here's an example:with open("stocks.txt", "r"):
data = f.read()
try-finally
approach here instead. Though, the with
statement simplifies our code to just two lines.def add_book(book_id, storage=[]):
storage.append(book_id)
return storage
my_book_list = add_book(1)
print(my_book_list)
my_other_book_list = add_book(2)
print(my_other_book_list)
# Expectation:
# [1]
# [2]
# Reality:
# [1]
# [1, 2] Huh, what? But they are different variables!
storage
in the example above) are created (i.e. evaluated) only once.add_book
function. Here, the same list is used over and over again instead of creating a new list.# Do:
def add_book(book_id, storage=None):
if storage is None:
storage = []
storage.append(book_id)
return storage
# Don't:
def generate_fruit_basket(fruits):
"""Without list comprehension"""
basket = []
for fruit in fruits:
if fruit != "grapes":
basket.append(fruit)
# Do:
def generate_fruit_basket_lc(fruits):
"""With list comprehension"""
return [fruit for fruit in fruits if fruit != "grapes"]
# Don't:
def get_book_price(inventory):
return [(book, price) for book in inventory if book.startswith('A') for price in inventory[book] if price > 10]
# Perhaps slightly better...? But please don't.
def get_book_price(inventory):
return [
(book, price) for book in inventory
if book.startswith('A')
for price in inventory[book]
if price > 10
]
# Do NOT ever use bare exception:
while True:
try:
input_string = input("Input something")
converted_input = int(input_string)
print(converted_input)
except: # Can't do Ctrl + C to exit!
print("Not a number!")
is
operator checks if the two items reference the same object (i.e. present in the same memory location). A.k.a reference equality.==
operator checks for value equality.
Here’s a brief example of what I mean:
# NOTE: In Python everything is an object, including list
listA = [1, 2, 3]
listB = [1, 2, 3]
listA is listB # False because they are NOT the same actual object
listA == listB # True because they are equivalent
Remember, listA
and listB
are different objects.
is
and ==
operator:# Do:
if foo is None:
...
# Don't:
if foo == None:
...
# Do:
if not bar:
...
# Don't:
if bar == False:
...
# Do:
if baz:
...
# Don't:
if baz is True:
...
# Don't
if baz == True:
...
import *
, you risk polluting the current namespace as it imports all the functions and classes from the library.import *
may clash with the functions defined by you.