Use this as a learning checklist. Solve each question yourself, test edge cases, and keep solutions in clearly named files. For networking and security exercises, use only systems, accounts, and packet captures you own or are explicitly authorized to test.
- Create variables for a student's name, age, room number, and CGPA. Print both their values and data types.
- Take two numbers as input and display their addition, subtraction, multiplication, division, floor division, modulus, and exponentiation.
- Explain with code when to use
int,float,str,bool, andNone. - Write a program that converts a user-entered age from a string to an integer safely (handle
ValueError). - Check whether a student is eligible for placement when CGPA is at least 7 and there are no backlogs.
- Predict the result of comparison and logical expressions using
and,or, andnot. - Swap two variables with and without using a temporary variable.
- Build a simple bill calculator that applies a percentage discount and tax in the correct order.
- Use the walrus operator (
:=) to assign and check a value inside awhileloop condition. - Explain the difference between
==andis; give one example where they produce different results. - Demonstrate bitwise operators (
&,|,^,~,<<,>>) on small integers and explain each result. - Use augmented assignment operators (
+=,-=,*=,//=,**=,%=) inside a loop.
- Write a program that checks whether an integer is even or odd.
- Write a voting-eligibility checker for a user aged 18 or older.
- Take three numbers and print the largest, including the case where values are equal.
- Create a grade calculator: 90–100 → A+, 80–89 → A, 70–79 → B, 60–69 → C, below 60 → Fail.
- Print the multiplication table for a number from 1 to 10.
- Find the sum of the first
Nnatural numbers using a loop. - Calculate a factorial using a loop. Handle zero and reject negative input.
- Accept 10 numbers and display how many are even and how many are odd.
- Keep asking for the password
future123until the correct password is entered (usewhile). - Build a number-guessing game that reports "Too High" or "Too Low" until the answer is correct.
- Compare
for,while,break,continue, andpassby writing one short example of each. - Validate numeric input so that non-numeric values do not crash your program.
- Use nested loops to print a right-angled triangle of stars with
Nrows. - Use
enumerate()to print each item in a list along with its index — avoid a manual counter variable. - Use
zip()to pair two lists of equal length and print each pair on one line.
- Print the first, last, and middle character of a string using positive and negative indexing.
- Reverse a string with slicing and check whether it is a palindrome.
- Given a sentence, demonstrate
upper,lower,title,replace,split,join,find,count,startswith,endswith, andstrip. - Count the vowels, consonants, digits, spaces, and special characters in a user-entered string.
- Write a program that normalizes a full name by removing extra spaces and applying title case.
- Use
len,max,min,sum,type,round,abs,sorted, andreversedin meaningful examples. - Find the longest word in a sentence after removing punctuation.
- Mask all but the final four characters of an account identifier without changing short identifiers.
- Use advanced f-string formatting: align text, pad numbers with leading zeros, show two decimal places, and format a large number with a thousands separator.
- Explain raw strings (
r"...") and when they are necessary (e.g., Windows file paths, regex patterns).
- Create a list of five programming languages, add one language, remove another, and explain the difference between
remove,pop, anddel. - Find the length, sum, minimum, maximum, and average of a list of 10 numbers.
- Print only the even numbers from a list of 10 numbers.
- Read five numbers from the user, store them in a list, and print the list in sorted and reversed order.
- Use a list comprehension to create squares of even numbers from 1 to 20.
- Remove duplicate values from a list while preserving the original order.
- Use
extend,insert,index,count,copy, andclearon a list and describe what each does. - Create a 2D list (matrix) and print its elements row by row using nested loops.
- Flatten a nested list using a list comprehension with two
forclauses.
- Create a tuple containing the seven days of the week and print the third item and the length.
- Check whether
"Python"is in("Java", "Python", "C", "JavaScript"). - Try changing a tuple item and explain the resulting
TypeError. - Count the occurrences of
10in(10, 20, 10, 30, 40, 10)and find the index of the first occurrence. - Unpack a tuple of student details into meaningful variable names.
- Convert a list to a tuple and explain a practical reason to choose an immutable sequence.
- Use a tuple as a dictionary key and explain why lists cannot be used as dictionary keys.
- Create a set with duplicate numbers and explain why duplicates disappear automatically.
- Add and remove student names from a set; use both
discardandremoveand explain their different behavior for missing values. - Find the union, intersection, difference, and symmetric difference of two sets.
- Determine whether one set is a subset, superset, or disjoint set of another.
- Find the common skills shared by two lists of technologies using sets.
- Take five numbers from the user and display only unique values using a set.
- Create a dictionary with
name,age, andcity, then update a value and add a new key. - Print all dictionary keys, values, and key-value pairs using
.keys(),.values(), and.items(). - Store marks for five students and print each name with its mark.
- Check whether the
agekey exists before accessing it; usegetandsetdefaultsafely. - Count word frequency in a sentence using a dictionary.
- Sort a dictionary of student marks by name and separately by marks (descending).
- Use a dictionary comprehension to invert a dictionary (swap keys and values).
- Merge two dictionaries using the
|operator (Python 3.9+) and explain what happens when keys clash.
- Write reusable functions for
is_even,calculate_grade, andcalculate_factorialwith docstrings. - Explain positional arguments, keyword arguments, default arguments,
*args, and**kwargswith one example each. - Return multiple values from a function and unpack them safely.
- Explain local, global, and
nonlocalscope by correcting a scope-related bug. - Create a module named
calculations.py, import it intomain.py, and useif __name__ == "__main__":correctly. - Create a small package with
__init__.pyand explain the difference between absolute and relative imports. - Organize a command-line project into
src/,tests/,data/,README.md, andrequirements.txt. - Write a function that accepts a callback function as an argument and calls it with a result.
- Write a
lambdathat squares a number and use it directly in an expression. - Use
lambdawithsorted()to sort a list of tuples by the second element. - Use
map()with alambdato convert a list of Celsius temperatures to Fahrenheit. - Use
filter()with alambdato keep only even numbers from a list. - Use
reduce()fromfunctoolswith alambdato compute the product of all numbers in a list. - Explain when a named function is preferable to a
lambdaand when alambdais the right choice.
- Write a decorator that logs a function's name, arguments, and return value before and after it runs.
- Use
functools.wrapsinside a decorator and explain why it preserves the wrapped function's__name__and__doc__. - Write a parameterized decorator (decorator factory) that measures execution time without changing the wrapped function.
- Write a decorator that retries a function up to
Ntimes after a temporary failure, with a configurable retry limit. - Write a generator function that yields Fibonacci numbers up to a user-defined limit.
- Explain generator expressions versus list comprehensions and compare their memory usage with
sys.getsizeof. - Use
yield fromto delegate to a sub-generator and combine two generators into one. - Write an infinite counter generator safely, then consume only the first 10 values using
itertools.islice. - Write a context manager using
withfor safe file access; then write a custom context manager class using__enter__and__exit__. - Create a
@contextmanager-based context manager (usingcontextlib) that reports whether a block completed successfully. - Implement an iterator class with
__iter__and__next__that yields a fixed number of countdown values.
- Create a
Studentclass with name, roll number, course, a constructor (__init__), and adisplaymethod. - Create an
Employeeclass that raises salary by 10% and displays the updated data. - Build a
BankAccountclass withdeposit,withdraw, anddisplay_balance; reject invalid withdrawals using a custom exception. - Explain instance attributes versus class attributes and show how they interact when modified on an instance.
- Demonstrate
@classmethodand@staticmethodusing one class — explain when to use each. - Use
@property,@<name>.setter, and@<name>.deleterto control read/write/delete access to a private attribute. - Create a
Personparent class and aStudentchild class that adds roll number and course (single inheritance). - Demonstrate multiple inheritance: create two parent classes and one child class that inherits from both; call
super()correctly. - Explain the Method Resolution Order (MRO) and print it with
ClassName.__mro__. - Demonstrate method overriding: create an
Animalparent class with aspeakmethod; override it inDogandCatchild classes. - Use composition: give a
Studentobject anAddressobject instead of inheriting unnecessarily. - Implement dunder/magic methods:
__str__,__repr__,__len__,__eq__,__lt__,__add__, and__contains__in one class. - Use
__slots__in a class and explain how it reduces memory usage compared to the default__dict__. - Use
@dataclassto define a data-holding class and compare it with an equivalent regular class that has__init__,__repr__, and__eq__. - Create an Abstract Base Class using
ABCand@abstractmethod; show that it cannot be instantiated directly.
- Create
student.txt, write your name, read it back, then append your city — usewith open(...)throughout. - Write multiple student records to a file and read them back; explain file modes
r,w,a,x,b, and+. - Handle
ValueError,ZeroDivisionError,FileNotFoundError, and a custom validation exception withtry/except/else/finally. - Create a custom exception class that inherits from
Exceptionand carries a descriptive error message. - Use a custom exception to reject invalid bank-account transactions.
- Demonstrate the difference between
raiseandraise ... from ...(exception chaining). - Create and activate a virtual environment named
.venv. - Install a package with
pip, generaterequirements.txtwith pinned versions, and reproduce the environment in a new virtual environment. - Explain why package versions should be pinned and how to check them for known vulnerabilities.
- Use the walrus operator (
:=) in awhileloop to read and process input without repeating the call. - Use
match/case(Python 3.10+) to handle HTTP status codes cleanly; include a wildcardcase _:fallback. - Use
match/casewith a sequence pattern to destructure a list and with a mapping pattern to destructure a dictionary. - Merge two dictionaries with
|and update one in-place with|=; explain what happens when keys overlap. - Show positional-only parameters (
/) and keyword-only parameters (*) in a function signature.
- Build a password strength checker that scores a password based on length, uppercase, lowercase, digits, and special characters. Print "Weak", "Medium", or "Strong".
- Add a password generator that creates a random password of a specified length using
secretsandstringmodules. - Add entropy calculation: estimate crack time assuming 10 billion guesses/second.
- Wrap the checker in a simple
tkinterGUI with a "Show/Hide password" toggle button. - Add a "Copy to clipboard" button using
pyperclip.
- Write a TCP port scanner using
socketthat scans ports 1–1024 on a given IP and prints open ports. - Add banner grabbing: after connecting to an open port, receive up to 1024 bytes and decode as UTF-8 (handle decode errors).
- Add threading with
threading.Threadand aqueue.Queueto scan multiple ports concurrently. - Add a timeout argument and implement connection timeout with
socket.setdefaulttimeout(). - Export scan results to a
.csvfile with columns: port, status, banner. - Add
--target,--start-port,--end-port, and--threadsCLI arguments usingargparse.
- Use
requeststo fetch a webpage andBeautifulSoupto parse and print all<h1>headlines. - Extract all hyperlinks (
<a href>) from a page and filter only external links (starting with http/https). - Save scraped headlines to a
.txtfile, one per line. - Add error handling for connection errors, timeouts, and non-200 status codes.
- Add a
User-Agentheader to avoid basic bot detection.
- Use
platformto print OS name, version, architecture, and hostname. - Use
uuidandgetmacto retrieve the machine's MAC address. - Use
requeststo queryhttps://ipapi.co/json/and extract public IP, ISP, city, country, and coordinates. - Format all data into a readable report and save to
system_info.txt. - Handle cases where the geolocation API is unreachable (timeout, HTTP error).
- Use
Counterto count word frequency in a sentence and print the three most common words. - Use
defaultdict(list)to group students by their grade without raising aKeyError. - Use
defaultdict(int)to count character frequencies without manually initializing keys. - Create a
namedtuplecalledPointwithxandyfields; access fields by name and by index. - Use
dequeto implement a fixed-size sliding-window buffer withmaxlen. - Use
dequeto efficiently rotate a sequence left and right without slicing. - Use
OrderedDictto preserve insertion order and compare it with a regulardict(Python 3.7+). - Use
ChainMapto merge two configuration dictionaries and explain lookup priority.
- Get today's date and the current date-time; print each in at least two different formats.
- Calculate a person's age in years from their birth date using
date.today(). - Add and subtract
timedeltaobjects (days, hours, minutes) from a date-time. - Parse a date string (
"2025-12-31") into adateobject usingstrptimeand format it back withstrftime. - Find the number of days remaining until a future event (e.g., New Year's Day next year).
- Explain the difference between
date,time,datetime, andtimedelta.
- Use
Pathto build file paths that work on both Windows and Linux without string concatenation. - Check whether a path exists, is a file, or is a directory using
Pathmethods. - List all
.pyfiles in a directory recursively usingPath.rglob("*.py"). - Read a file's full contents and write new contents using
Path.read_text()andPath.write_text(). - Extract the file name, stem (name without extension), suffix (extension), and parent directory from a path.
- Create a new directory and all necessary parent directories using
Path.mkdir(parents=True, exist_ok=True). - Resolve a user-supplied path with
Path.resolve()and confirm it starts with the expected root usingPath.is_relative_to().
- Use
os.getcwd(),os.listdir(),os.path.join(),os.path.exists(), andos.path.getsize()in one script. - Read environment variables with
os.environ.get()and provide a safe default when a variable is missing. - Use
os.walk()to print all files and directories under a given folder recursively. - Use
sys.argvto read command-line arguments and print a usage message when required arguments are missing. - Use
sys.exit()with a non-zero exit code to signal an error from a script. - Explain the difference between
os.pathandpathlib.Pathand when to prefer each.
- Use
itertools.chain()to iterate over multiple lists as if they were one sequence. - Use
itertools.islice()to safely consume only the firstNvalues from an infinite generator. - Use
itertools.count(),itertools.cycle(), anditertools.repeat()and explain a use case for each. - Use
itertools.combinations()anditertools.permutations()to generate all possible selections from a list. - Use
itertools.product()to generate a Cartesian product (e.g., all suit–rank pairs for a deck of cards). - Use
itertools.groupby()to group a sorted list of records by a key field. - Use
itertools.accumulate()to compute running totals of a list of values. - Use
itertools.takewhile()anditertools.dropwhile()to filter a sequence based on a predicate.
- Use
functools.reduce()to compute the product of a list without an explicit loop. - Use
functools.partial()to create a specialized version ofpowthat always cubes its argument. - Use
functools.lru_cache()to memoize a recursive Fibonacci function and measure the speed difference. - Use
functools.wrapsin a decorator and explain what is lost if you omit it. - Use
functools.total_orderingto define only__eq__and__lt__on a class and automatically get all other comparison methods.
- Write a command-line script that accepts
--input FILE,--output FILE, and--verboseflags usingargparse. - Add
--helptext, a--versionflag, and a required positional argument to anargparseparser. - Use
type=intandchoices=[...]inargparseto validate numeric and enumerated arguments automatically. - Use subcommands (
add_subparsers) to build a CLI tool withcreate,read, anddeletesub-commands. - Parse a list of values with
nargs="+"and explain the difference fromnargs="*".
- Configure the
loggingmodule withDEBUG,INFO,WARNING,ERROR, andCRITICALlevels; show which messages appear at each level. - Write logs to a rotating file with
logging.handlers.RotatingFileHandlerthat caps log size and keeps three backups. - Use a custom log formatter that includes timestamp, level, module name, and line number.
- Log a caught exception with full traceback using
logging.exception()inside anexceptblock. - Demonstrate how to redact a sensitive field (e.g., an API token) from log output using a custom
logging.Filter. - Use separate loggers per module with
logging.getLogger(__name__)and explain why this is better than the root logger.
- Run a simple shell command using
subprocess.run()withcapture_output=Trueand print its stdout. - Compare
subprocess.run(shell=True, ...)with a list-based invocation; explain the security risk ofshell=True. - Check the return code of a subprocess and raise an error if it is non-zero using
check=True. - Pass environment variables to a subprocess with the
envparameter without leaking parent-process secrets. - Use
subprocess.Popento start a long-running process, read its output line by line, and terminate it cleanly.
- Write patterns to validate an email-like string, an IPv4 address, a date (
YYYY-MM-DD), and a phone number. - Use
re.search,re.match,re.findall,re.finditer,re.sub, andre.splitand describe how each differs. - Explain raw strings (
r"..."), groups(), named groups(?P<name>...), quantifiers (*,+,?,{n,m}), and anchors (^,$). - Extract log entries using a named-group pattern for timestamp, severity, and message.
- Write tests that distinguish valid IPv4 addresses from look-alike invalid strings (e.g.,
256.0.0.1). - Redact an API token or password from a log line using
re.sub. - Explain catastrophic backtracking and rewrite a vulnerable pattern safely.
- Use
json.load,json.dump,json.loads, andjson.dumpsto read, modify, and write a JSON configuration file. - Validate that a JSON configuration has all required keys and correct value types before using it.
- Read a CSV with
csv.DictReader, validate required columns, and write a cleaned output CSV withcsv.DictWriter. - Detect malformed CSV rows, report their line numbers, and continue processing valid rows without crashing.
- Convert validated CSV records to a structured JSON file; report rows that could not be converted.
- Parse a local XML document with
xml.etree.ElementTree, extract selected elements, and turn records into dictionaries. - Explain why untrusted XML should be parsed with defenses against XML bomb and XXE attacks.
- Load YAML configuration with
yaml.safe_load, validate expected fields, and explain whyyaml.loadwithout aLoaderis dangerous. - Build a file-normalization utility that reads CSV, JSON, XML, or YAML and produces one validated JSON output format.
- Add type hints to a function using
int,str,float,bool,-> None, andlist[int](Python 3.9+). - Use
Optional[str]andUnion[int, str]to annotate parameters that may beNoneor multiple types. - Use
Callable[[int, int], int]to annotate a function that accepts another function as a parameter. - Use
TypeVarto write a genericidentityfunction that preserves the return type. - Use
TypedDictto define the expected shape of a dictionary and annotate a function that accepts it. - Run
mypyon a small module, interpret all reported type errors, and fix them. - Explain
Anyand when its use defeats the purpose of type checking.
- Split a URL into scheme, host, path, and query components using
urlparse. - Build an API URL safely from a base URL and user-supplied query values using
urlencode. - Encode and decode URL-percent-encoded strings with
quoteandunquote. - Identify and reject URL schemes other than
httpsin a downloader configuration. - Use
urljointo resolve relative links found in parsed HTML.
- Build a menu-driven ATM: check balance, deposit, withdraw, and exit — prevent overdrafts and validate all input.
- Build a student result manager: accept several students' names, marks, and attendance; print pass/fail, grade, percentage, and an attendance warning. Validate marks (0–100), attendance (0–100), and duplicate student names.
- Save the student result manager's records to a file and reload them when the program starts.
- Refactor the result manager into a package with separate modules for models, services, utilities, and the CLI entry point.
- Add a search feature that finds a student by name or roll number.
- Add an edit/delete menu option, confirm the action, and save updated data safely.
- Write automated
pytesttests for the grade, attendance-warning, deposit, and withdrawal rules. - Write a menu-driven contact book using functions, lists, dictionaries, file storage, and input validation.
- Create a command-line expense tracker that calculates category totals and monthly spending.
- Read a text file and report its line count, word count, character count, and most frequent word.
- Build the Hangman game: random word selection, masked display, limited guesses, and a replay option.
- Write a subdomain enumerator that reads from a wordlist file and uses
dnspython(dns.resolver.resolve) to check if each subdomain resolves. - Add threading with
concurrent.futures.ThreadPoolExecutorto run DNS lookups in parallel. - Record only subdomains that return an
Arecord and save them to a file. - Add a rate-limiting delay between requests to avoid DNS flooding.
- Handle
NXDOMAIN,NoAnswer, andTimeoutexceptions fromdnspythongracefully.
- Read a large log file line by line (stream, do not load into memory) using
open()and iterate. - Use
reto extract: IPv4 addresses (�\d{1,3}(\.\d{1,3}){3}�), HTTP status codes, and timestamps. - Count occurrences of each IP and print the top 10 most frequent using
collections.Counter. - Extract indicators of compromise (IOCs): IPs, domain names, MD5/SHA256 hashes, and URLs — write each to a separate output file.
- Add CSV output with
csv.DictWriter: columns for timestamp, IP, status code, and URL. - Parse a JSON-format log file and extract the same fields using
json.loads().
- Use
requests.Session()to make authenticated API calls with a Bearer token set in session headers. - Write a function that checks if an API endpoint returns the expected HTTP status code and content-type header.
- Add retry logic with exponential backoff using
time.sleepand a loop. - Use
jsonto parse the response and extract nested fields; handleKeyErrorandJSONDecodeError. - Store API keys in environment variables using
os.getenv()— never hardcode credentials.
- Use
scapyto sniff 10 packets on the default interface and print the source IP, destination IP, and protocol. - Filter captured packets for only TCP packets and print the destination port.
- Read a
.pcapfile usingscapy.rdpcap()and count how many packets are HTTP vs HTTPS. - Use
pysharkto capture packets and print HTTP request methods and URIs. - Write a packet summary to a CSV: timestamp, src_ip, dst_ip, protocol, length.
- Build a Discord bot with
discord.pythat handles at least three commands:!ping,!userinfo, and!help— each with a formatted embed response. - Add a
!userinfocommand that returns the sender's username, ID, joined date, and roles. - Load the bot token from an environment variable; refuse to start if the variable is missing.
- Deploy the bot to run continuously with reconnect logic and log all events to a rotating file.
- Write a command that reads from a local JSON config file and responds with configurable data.
- Open a suspicious binary file in
rbmode and usere.findallto extract all printable ASCII strings of length ≥ 6. - Search extracted strings for IOC patterns: IPv4s, domains, URLs, file paths, registry keys.
- Compute MD5, SHA1, and SHA256 hashes of the file using
hashlib. - Look up the SHA256 hash against VirusTotal's public API and print the detection ratio.
- Write a report with all findings to a JSON file.
- Write a web crawler using
requests+BeautifulSoupthat starts from a seed URL and collects all links up to depth 2. - Add deduplication using a
setand respectrobots.txtby checking it withurllib.robotparser. - Write a directory brute forcer that reads a wordlist and sends GET requests to
base_url/word; record all non-404 responses. - Use
Seleniumto render a JavaScript-heavy page and extract dynamic content not available viarequests. - Add
urllib.parse.urljointo properly resolve relative URLs to absolute.
-
⚠️ Lab/test systems only. Usepynput.keyboard.Listenerto capture keystrokes and write them to a log file with timestamps. - Use
win32gui.GetWindowText(win32gui.GetForegroundWindow())to log the active window title alongside keystrokes. - Use
getmac.get_mac_address()andrequeststo log the system's MAC and public IP at startup. - Use
smtplibto email the log file to yourself every N minutes; store credentials in environment variables. - Add a stop mechanism: listen for a secret key combination to stop logging cleanly.
-
⚠️ Security awareness only, local use. UseFlaskto serve an HTML login form atlocalhost:5000. - Log any submitted form data (username, password) to a local file.
- Add hidden fields to demonstrate autofill filling fields the user cannot see.
- Add a results page that shows what data was captured, to demonstrate the risk to users.
-
⚠️ Offline/local only. UseFlask+Jinja2to serve a cloned-looking login page. - Store submitted credentials to a local JSON log file.
- After submission, redirect the user to the legitimate site (or a "wrong password" page).
- Add a
/adminroute that shows all captured entries — password-protected with a hardcoded admin token.
-
⚠️ Education only. Usezipfileto append a.exefile to the end of a.jpgimage. - Script a steganography awareness demo: combine a
.jpgand a text payload using binary append; verify the resulting file still opens as an image. - Use
pyinstallerto compile a Python script to a standalone.exewith--onefile. - Explain what a "polyglot file" is and why antivirus tools may or may not detect this technique.
- Explain IP addresses, ports, sockets, TCP, UDP, client–server architecture, and the TCP three-way handshake.
- Explain the differences among HTTP, HTTPS, DNS, TLS, and SSH.
- Use
socket.gethostbynameandsocket.getaddrinfoto resolve a hostname and compare the results. - Describe DNS record types A, AAAA, CNAME, MX, NS, TXT, and PTR; explain the purpose of each.
- Explain private versus public IP ranges, loopback addresses, and why
127.0.0.1is useful for practice. - Trace the full lifecycle of an HTTPS request: DNS lookup → TCP connect → TLS handshake → HTTP request/response.
- Explain NAT, firewalls, proxies, and load balancers at a conceptual level.
- Convert a port number to a service name using
socket.getservbyport.
- Create a TCP echo server bound to
127.0.0.1and a matching client that sends and receives text. - Extend the TCP server to serve multiple local clients using threads.
- Create a UDP client and server on localhost; explain how UDP differs from TCP in reliability and ordering.
- Add connection timeouts, safe message framing (length-prefix protocol), structured logging, and clean shutdown to the TCP server.
- Build a local chat application with usernames and broadcast messages to all connected clients.
- Test a localhost server with malformed, oversized, and empty input; reject invalid messages gracefully.
- Use
selectorsorasyncioto handle multiple local client connections without one thread per client. - Write a localhost TCP time server that returns the current ISO timestamp when a client sends
TIME\n. - Add a
QUITcommand to a local client/server pair that closes the connection cleanly on both ends. - Demonstrate the difference between a blocking and a non-blocking socket with a short local example.
- Send HTTP GET, POST, PUT, PATCH, and DELETE requests with
requeststo a safe test API; inspect status code, headers, and JSON response. - Explain REST resources, HTTP methods, status codes (2xx, 3xx, 4xx, 5xx), query parameters, headers, and pagination.
- Write a client that authenticates to a documented test API using a Bearer token stored in an environment variable.
- Implement exponential backoff with jitter for transient failures; respect a
Retry-Afterheader when present. - Compare certificate verification enabled vs disabled; explain why verification must never be disabled in production.
- Use
sslto inspect the certificate presented by an HTTPS host (subject, issuer, validity dates). - Use
dnspythonto perform a PTR (reverse DNS) lookup for a given IP address and handleNXDOMAINgracefully. - Resolve a hostname to all returned IPv4 and IPv6 addresses; print results in a readable table.
- Use
urllib.parse.urljointo resolve relative redirect URLs returned by an HTTP response into absolute URLs. - Fetch several permitted URLs concurrently with
asyncio.gatherand limit concurrency withasyncio.Semaphore. - Write the same I/O-bound networking task three ways —
threading,multiprocessing, andasyncio— and compare performance and code complexity. - Measure sequential vs concurrent request time for several local or permitted HTTP requests.
- Explain how a client should handle: DNS failure, connection refused, timeout, TLS verification failure, and a 500 response.
- Write a basic
async defcoroutine and run it withasyncio.run(). - Use
await asyncio.sleep()inside a coroutine and explain the difference fromtime.sleep(). - Create multiple tasks with
asyncio.create_task()and gather their results withasyncio.gather(). - Use
asyncio.Queueto implement a producer–consumer pattern where multiple producers and consumers run concurrently. - Handle
asyncio.TimeoutErrorby wrapping a coroutine withasyncio.wait_for(coroutine, timeout=5). - Explain the difference between a coroutine, a task, and a future in
asyncio.
- requests: Use
Sessionobjects, custom headers, query parameters, cookies, basic auth, and bearer tokens. - requests: Download a permitted JSON resource, validate its content type, and save a formatted local copy.
- requests: Create an HTTP client wrapper that retries only idempotent requests after selected transient status codes.
- BeautifulSoup (bs4): Parse a saved HTML file and extract page title, links, headings, tables, and elements by CSS selector.
- BeautifulSoup (bs4): Extract all unique, absolute links from a saved HTML page using
urljoin. - BeautifulSoup (bs4): Parse a local HTML table into a list of dictionaries and export it as CSV.
- BeautifulSoup (bs4): Parse pagination links from saved HTML and deduplicate the resulting URLs.
- BeautifulSoup (bs4): Build a polite scraper for a site you control, respecting its terms,
robots.txt, rate limits, and errors. - Selenium: Automate a local or permitted test page: open it, fill a form, wait for dynamic content, take a screenshot, and close the driver.
- Selenium: Write stable selectors and explain why explicit waits are safer than fixed
time.sleepdelays. - Selenium: Test validation messages on a form in a local demo page without using fixed sleeps.
- Selenium: Capture browser console errors from a local test application and include them in a test report.
- Compare
requests, BeautifulSoup, and Selenium: state when each is the appropriate choice. - Write a web-automation configuration that defines a target allowlist, rate limit, timeout, and user agent.
- socket: Build an authorized localhost service checker that tests a fixed allowlist of ports and reports open/closed/error states.
- socket: Write a function that validates hostnames and ports before attempting a connection to an authorized target.
- socket: Use
socket.create_connectionwith a timeout and return structured success or failure data. - socket: Implement a banner reader only for a service you operate or are authorized to test; handle timeouts gracefully.
- dnspython: Enumerate A, AAAA, MX, NS, and TXT records for a domain you are authorized to query.
- dnspython: Retrieve MX records, sort them by priority, and print a readable mail-routing summary.
- dnspython: Compare a domain's A and AAAA records, and explain what an empty answer means.
- dnspython: Handle DNS timeouts and
NXDOMAINresponses without crashing. - scapy: Create and inspect packets in an isolated lab or offline PCAP; identify Ethernet, IP, TCP, UDP, and ICMP fields.
- scapy: Analyze a lab capture to count protocols, flag malformed fields, and extract DNS query names — without transmitting traffic.
- scapy: Load an offline capture and count TCP flags: SYN, ACK, FIN, RST.
- pyshark: Read an offline PCAP and summarize source/destination pairs, protocols, ports, and packet counts.
- pyshark: Filter an offline PCAP for DNS or HTTP traffic and export a small CSV summary.
- Compare Scapy and PyShark: installation, packet representation, filtering capabilities, and best use cases.
- platform: Print OS name, version, machine type, and Python implementation using
platform.system(),platform.version(),platform.machine(), andplatform.python_implementation(). - platform: Detect whether the script is running on Windows, Linux, or macOS and branch behavior accordingly.
- platform: Use
platform.node()to retrieve the machine's hostname andplatform.processor()for CPU info. - uuid: Generate a UUID4 with
uuid.uuid4()and explain why UUID4 is preferred for random identifiers over sequential IDs. - uuid: Generate a UUID5 (namespace + name) and explain the difference from UUID4.
- getmac: Retrieve the MAC address of the default network interface with
getmac.get_mac_address(); handle the case where no MAC is found. - getmac: Retrieve the MAC address for a specific remote IP using
get_mac_address(ip="x.x.x.x")and explain what ARP cache lookups mean. - smtplib: Connect to an SMTP server over TLS (port 587) with
smtplib.SMTPandstarttls(); authenticate with credentials stored in environment variables. - smtplib: Send a plain-text email using
sendmail(); construct the message string with the correctTo:,From:,Subject:headers. - email + ssl: Build a structured email using
email.mime.text.MIMETextandemail.mime.multipart.MIMEMultipart; add a plain-text and an HTML part. - email + ssl: Attach a file to an email using
email.mime.base.MIMEBaseandencoders.encode_base64(). - email + ssl: Wrap an SMTP connection in
ssl.create_default_context()for port 465 (implicit TLS) and explain the difference from STARTTLS. - zipfile: Create a
.ziparchive from a list of files usingzipfile.ZipFilein write mode. - zipfile: Extract all files from a
.ziparchive to a target directory; list archive contents without extracting usingnamelist(). - zipfile: Read a file directly from inside a
.zipwithout extracting it to disk. - zipfile: Create a password-protected ZIP archive and explain why ZIP encryption is weak and what to use instead for secure archiving.
- zipfile: Detect whether a
.jpgor.pngfile has appended ZIP data by checking for aPKmagic byte signature at non-zero offsets. - pyinstaller: Compile a Python script to a standalone executable with
pyinstaller --onefile script.py; explain what thedist/directory contains. - pyinstaller: Use a
.specfile to customize the build: add hidden imports, include data files, and change the output name. - pyinstaller: Explain what UPX compression does to the final executable and when to disable it.
- discord.py: Create a Discord bot using
discord.ext.commands.Bot; respond to a!pingcommand withPong!. - discord.py: Use
@bot.eventandon_readyto confirm the bot is online; useon_messageto log all messages in a channel. - discord.py: Add an async background task with
tasks.loop(seconds=60)that posts a message to a channel on a timer. - discord.py: Load the bot token from an environment variable; explain why hardcoding tokens in source code is a critical security risk.
- discord.py: Add error handling so the bot responds with a friendly message on
CommandNotFoundand logs the unknown command. - pynput: Use
pynput.keyboard.Listenerto start and stop a keyboard listener; log eachkey_pressevent with a timestamp. - pynput: Use
pynput.mouse.Listenerto track mouse click events (button, position, pressed/released) in a lab environment. - pynput: Stop a
pynputlistener cleanly by raisingStopExceptionfrom inside the callback. - win32gui (Windows only): Use
win32gui.GetForegroundWindow()andwin32gui.GetWindowText()to retrieve the title of the currently active window. - win32gui (Windows only): Poll the active window title every second; log a new entry only when the title changes.
- markdown + html2text: Convert a Markdown string to HTML using the
markdownlibrary; convert HTML back to Markdown usinghtml2text.html2text(). - markdown + html2text: Read a
.mdfile, convert it to HTML, and write the result to a.htmlfile. - Flask (expand): Create a Flask app with at least three routes:
GET /,POST /submit, andGET /results; useflask.request.formto read form data. - Flask (expand): Use
flask.redirectandflask.url_forto redirect a user after a form submission (Post/Redirect/Get pattern). - Flask (expand): Use
flask.jsonifyto return a JSON response from an API endpoint; set the correctContent-Typeheader. - Flask (expand): Protect a Flask route with a simple token check: read the token from an environment variable and reject requests that do not match.
- Flask (expand): Explain Flask's debug mode: what it enables, why it must never be on in production, and how to disable it.
- Jinja2: Use
{{ variable }}and{% if %}...{% endif %}blocks in a Jinja2 template to render dynamic HTML. - Jinja2: Use
{% for item in list %}to render a list of items in a template; useloop.indexfor row numbers. - Jinja2: Apply Jinja2 filters:
{{ value | upper }},{{ value | default("N/A") }},{{ value | truncate(50) }}. - Jinja2: Use
{% extends "base.html" %}and{% block content %}to inherit a base template layout. - Jinja2: Explain what auto-escaping does in Jinja2 and why it must be enabled when rendering user-supplied data in HTML.
- cryptography: Hash a message with SHA-256 and explain why passwords need a dedicated scheme (e.g., bcrypt, Argon2) rather than plain hashing.
- cryptography: Generate a Fernet key, encrypt a local test message, and prove that altering the ciphertext causes decryption to fail.
- cryptography: Derive an encryption key from a password using a salt and an approved KDF (e.g., PBKDF2HMAC or Scrypt).
- cryptography: Generate a signing key pair, sign a message, and verify the signature; explain what a valid signature proves.
- cryptography: Inspect an X.509 certificate's subject, issuer, validity period, and public key algorithm.
- cryptography: Verify certificate validity dates and report whether a certificate is currently valid.
- cryptography: Rotate a symmetric encryption key in a test application without exposing either key in source control.
- cryptography: Compare hashing, encryption, encoding, and signing — give one practical example of each.
- paramiko: Connect to an SSH server you administer using key-based authentication and run a harmless command.
- paramiko: Upload and download a test file over SFTP with host-key verification enabled.
- paramiko: Load a private key from a protected local path without printing its contents.
- paramiko: Use a known-hosts file and explain how it prevents connecting to an unexpected server.
- paramiko: Transfer a test directory listing over SFTP and handle connection and authentication failures cleanly.
- Explain the purpose of SSH host-key verification and the risk of automatically accepting unknown host keys.
- Design a key-rotation plan for an application that uses encrypted configuration values.
- pwntools (learn later): Set up an isolated CTF or intentionally vulnerable local binary environment and learn the library's basic process and ELF-inspection APIs.
- pwntools (learn later): Practice only against CTF targets or binaries you own; document the target, authorization, and cleanup steps for every exercise.
- pwntools (learn later): Explain architecture, endianness, registers, and calling conventions before using the library.
- pwntools (learn later): Read an ELF's basic metadata in a CTF lab and explain PIE, NX, RELRO, and stack canaries at a high level.
- pwntools (learn later): Write a lab report that focuses on mitigation learning and defensive fixes, not deployment against real targets.
-
⚠️ Authorized networks only. Write a script that attempts outbound TCP connections on ports 80, 443, 53, 8080, 8443, 22, and 21 and reports which succeed. - Use
subprocessto callcurland capture its exit code for each port test. - Use
threadingto test all ports concurrently and collect results in adict. - Output a report:
port, protocol, reachable (yes/no).
- Build a scanner that accepts a target host and checks for open ports (using socket), banner grabs, and known vulnerable banners (e.g., outdated vsftpd version).
- Add a module that checks HTTP response headers for missing security headers (
Strict-Transport-Security,X-Frame-Options,Content-Security-Policy). - Add a module that checks for default credentials on common services (FTP, SSH) using a small wordlist —
⚠️ authorized targets only. - Output findings as a structured JSON report.
- Build a localhost port checker with a small allowlist, connection timeout, clear consent prompt, and CSV/JSON report.
- Build an authorized banner grabber for your own test services, with rate limiting and graceful error handling.
- Build a directory/content discovery tool only for a lab site you own; include a fixed target scope, delay, and audit log.
- Build a web crawler for your own site that respects scope,
robots.txtrules, depth limits, duplicate URLs, and rate limits. - Build a log analyzer that extracts timestamps, levels, IPs, URLs, and error patterns from local logs using
re. - Build an IOC extractor for local text files that finds and deduplicates domains, IPs, URLs, and hashes, then exports a report.
- Build an API automation client with configuration files, retries, pagination, structured logs, and unit tests.
- Build an HTML or Markdown report generator from structured JSON/CSV results.
- Build a vulnerability configuration checker for an application or infrastructure you own; make checks non-destructive and explain every finding.
- Build an offline packet parser that summarizes a provided PCAP without capturing or transmitting live traffic.
- Add
argparseoptions (--help,--dry-run,--verbose,--output), input validation, and meaningful exit codes to one of your automation projects. - Add a dry-run mode that prints what the tool would do without making network requests or modifying files.
- Add structured JSON logs with a unique run identifier to an automation tool.
- Create a configuration schema and validate all configuration fields before the project begins work.
- Add rate limiting and a maximum-runtime safeguard to a permitted crawler or service checker.
- Generate both an executive summary and a technical-detail report from the same structured result data.
- Write unit tests using mocked network responses rather than relying on live internet services.
- Create a cleanup routine that closes files, sockets, and browser drivers even after errors.
- Validate type, length, range, format, and allowlisted values for every external input a script accepts.
- Create a validation function for a user record; test empty, oversized, malformed, and valid values.
- Explain why
eval,exec, unsafe deserialization, unchecked subprocess calls, and string-built SQL are dangerous; demonstrate safe alternatives. - Use
pathlibto ensure a requested output file remains inside an allowed project directory (prevent path traversal). - Design error messages for users and log entries for developers — without exposing secrets, stack traces, or internal infrastructure details.
- Store a sample API token in an environment variable, confirm that logs redact it, and verify it is excluded from version control.
- Load secrets from environment variables or an approved secret manager; add
.envand private keys to.gitignore. - Separate configuration by environment (development, test, production) and validate it at startup.
- Use virtual environments, version pinning, dependency review, and vulnerability scanning as part of dependency management.
- Create a dependency-update checklist that includes tests, changelog review, and vulnerability checks.
- Configure rotating logs and verify that an exception is recorded with useful, non-sensitive context.
- Write docstrings, type hints, a README setup guide, and a responsible-use statement for every security-related tool you build.
- Review one project for hard-coded secrets, overly broad permissions, unsafe defaults, and missing error handling.
- Add a security section to a README describing authorized use, data handling, and a process for reporting issues.
- Use a debugger (
pdbor IDE breakpoints) to trace a failing program and identify the root cause — avoid relying onprintstatements. - Profile a slow function with
cProfile; identify the bottleneck and fix it using measured evidence. - Write
pytestunit tests covering normal cases, boundary values, invalid input, and expected exceptions for one project. - Use
pytestfixtures to share setup code across tests and@pytest.mark.parametrizeto cover multiple input cases in one test function. - Write a failing test before fixing a bug (test-driven approach); demonstrate that the test passes after the fix.
- Mock a file, clock, or network dependency in a unit test using
unittest.mock.patch; explain why the mock is necessary. - Format code with
black(orautopep8), lint it withflake8orruff, and explain each category of issue you fix. - Add type hints to a module and run
mypyto find and fix all reported type errors. - Initialize a Git repository, make atomic focused commits, use a feature branch, resolve a simple merge conflict, and write a useful
.gitignore. - Write a descriptive commit message following a convention (e.g., Conventional Commits) and explain why commit messages matter.
- Create a
README.mdthat describes purpose, installation, configuration, usage, tests, limitations, and authorization boundaries. - Conduct a self-code-review checklist covering naming, complexity, duplication, tests, error handling, security, and documentation.
- Set up a formatter, linter, and test command that any developer can run consistently from the project root.
- Create a release checklist that verifies tests pass, dependencies are pinned, version number is bumped, documentation is current, and configuration defaults are safe.
- Build a Flask app with routes for each tool (port scanner, subdomain enumerator, log analyzer).
- Use
flask.requestto accept form input (target IP, domain, log file path) and return results on the same page. - Add Bootstrap styling with a navbar linking all tools.
- Run tool functions in a background thread and show a "scanning..." message while waiting.
- Use
smtplibandemail.mime.text.MIMETextto send a plain-text email over TLS (port 587). - Read SMTP credentials from environment variables.
- Write a watcher function that monitors a log file for a pattern (e.g., "FAILED LOGIN") and sends an alert email when found.
- Add attachment support: send the log file as an email attachment using
email.mime.multipart.
- Build a professional Python automation or security-oriented tool from scratch with a clear scope, modular design, tests, documentation, secure configuration, logging, and a reproducible environment.
- Explain every dependency and major design decision in the tool.
- Demonstrate that the tool handles valid input, invalid input, expected failures, and cleanup correctly.
- Package the tool so a new user can install and run it from documented instructions alone.
- Produce a sample report using only synthetic or authorized data.
- Review the tool against a security checklist before every release.
- Obtain explicit written authorization and define scope before testing any non-local system.
- Present the tool's limitations and safe-use boundaries to another learner.
- Build one original automation or security tool from scratch — clean structure, full tests, complete docs, and secure configuration included.