Lazo Lab Sign up

Guides

Python for beginners

Beginner 路 10 min read

Variables, loops, functions and files, then a real security script at the end.

Why Python?

Python reads almost like English and comes with tools for files, networking, hashing and randomness built in. It's the most popular language in security, data and automation.

Variables and input

name = input("What's your name? ")
age = int(input("How old are you? "))
print(f"Hi {name}, next year you'll be {age + 1}.")

Decisions and loops

for n in range(1, 16):
    if n % 15 == 0:
        print("FizzBuzz")
    elif n % 3 == 0:
        print("Fizz")
    elif n % 5 == 0:
        print("Buzz")
    else:
        print(n)

Functions

A function is a reusable block of code with a name. Give it inputs, get an output.

def is_strong(password):
    return len(password) >= 14 and not password.isalpha()

print(is_strong("hello"))                 # False
print(is_strong("lamp-river-cactus-9"))   # True

Your first security script

This counts visitors per IP in a web server log, the same idea behind the admin dashboards people use to spot bots.

from collections import Counter

counts = Counter()
with open("access.log") as log:
    for line in log:
        ip = line.split()[0]
        counts[ip] += 1

for ip, hits in counts.most_common(5):
    print(hits, ip)

Next steps

Head to the Challenges page and work through the Python basics track. Thirty small programs, each one building on the last.