02 intermediate

The basics get you a script These get you a script you can hand to someone else without shame

Table of Contents

f strings

F strings landed in Python 3.6 and replaced the old formatting mess Use them

user = "alice"
role = "admin"

# old
print("User: %s, Role: %s" % (user, role))
print("User: {}, Role: {}".format(user, role))

# current
print(f"User: {user}, Role: {role}")

The f prefix is not optional Write print("{user}") and you get the literal braces , not the value

Comprehensions

A comprehension builds a list in one line A loop does the same in four Pick the one the next reader can parse fastest

squares = []
for i in range(5):
    squares.append(i * i)

squares_comp = [i * i for i in range(5)]
print(squares == squares_comp)  # True

Do not stack three filters into one line to look clever Clever code is how you spend an hour debugging a condition you wrote yourself

Files

A with block around open() closes the file even when the body throws Use it every time

# writing
lines_to_write = ["line 1", "line 2"]
with open("my_file.txt", "w") as f:
    for line in lines_to_write:
        f.write(line + "\n")

# reading
try:
    with open("my_file.txt", "r") as f:
        content = f.read()
        print(content)
except FileNotFoundError:
    print("The file does not exist")

w overwrites Use a when you mean append Getting that wrong is a great way to destroy a log you needed

Exceptions

Things break Catch the exception you expect , not everything

try:
    result = 10 / 0
except ZeroDivisionError as e:
    print(f"Error: cannot divide by zero. ({e})")
finally:
    print("This block always executes")

Bare except: swallows KeyboardInterrupt and hides the bug you were looking for Catch the specific class

Classes

A class is a blueprint You define it once and build objects from it

class Target:
    def __init__(self, ip_address, port):
        self.ip_address = ip_address
        self.port = port
        self.is_vulnerable = False

    def display(self):
        return f"{self.ip_address}:{self.port} (Vulnerable: {self.is_vulnerable})"

target1 = Target("192.168.1.100", 443)
target1.is_vulnerable = True
print(target1.display())

self is the instance If you forget it in the method signature , every call fails with a confusing argument error

Common errors

  • TypeError: missing 1 required positional argument -> you forgot self
  • FileNotFoundError -> wrong path or the file was never created
  • AttributeError -> the object does not have that attribute , check the constructor

Fix the cause , not the traceback The traceback is a map , not the destination

Posted