This repository documents my personal journey through QA Engineering, Cybersecurity, and Networking.
It serves as a central place to store my technical notes, code examples, and learning reflections as I grow in the IT field.
All notes come from hands-on labs, formal training, and self-study — continuously updated as I learn.
| Command | Meaning | Example |
|---|---|---|
. or no special character |
Current directory | cd ./logs |
.. |
Parent directory | cd .. |
/ |
Root directory | cd / |
~ |
Home directory | cd ~ |
Here’s a list of the most commonly used and essential Linux commands for beginners.
These help you navigate, manage files, and perform basic operations in the terminal.
| Command | Description | Example |
|---|---|---|
pwd |
Prints the current working directory (where you are) | pwd |
ls |
Lists files and folders in the current directory | ls -l |
cd |
Changes the current directory | cd Documents |
mkdir |
Creates a new directory (folder) | mkdir new_folder |
rmdir |
Deletes an empty directory | rmdir old_folder |
rm |
Removes files | rm file.txt |
rm -r |
Removes a directory and its contents recursively | rm -r folder_name |
cp |
Copies files or directories | cp file.txt /home/user/Desktop |
mv |
Moves or renames files or directories | mv file.txt newfile.txt |
touch |
Creates a new empty file or updates its timestamp | touch notes.txt |
cat |
Displays the contents of a file | cat file.txt |
echo |
Displays text or writes text to a file | echo "Hello" > greeting.txt |
man |
Displays the manual for a command (help guide) | man ls |
clear |
Clears the terminal screen | clear |
history |
Shows a list of recently used commands | history |
whoami |
Prints your current username | whoami |
uname -a |
Displays system and kernel information | uname -a |
df -h |
Shows disk space usage | df -h |
du -sh |
Displays the size of the current directory | du -sh |
top |
Shows running processes and system resource usage | top |
sudo |
Executes a command as a superuser (admin privileges) | sudo apt update |
apt update |
Updates the list of available packages | sudo apt update |
apt upgrade |
Installs available package upgrades | sudo apt upgrade |
exit |
Closes the terminal or SSH session | exit |
💡 Tip: Use --help after any command (for example, ls --help) to quickly see its available options and usage examples.
Linux is a multi-user system where every file and directory has permissions that define who can read, write, or execute it.
Understanding and managing permissions is essential for security and proper system administration.
| Command | Description | Example |
|---|---|---|
ls -l |
Lists files in long format, showing permissions and ownership | ls -l |
chmod |
Changes file or directory permissions (read, write, execute) | chmod 755 script.sh |
chown |
Changes the ownership of a file or directory | sudo chown user:group file.txt |
chgrp |
Changes the group ownership of a file or directory | sudo chgrp developers project/ |
umask |
Sets default permission settings for new files | umask 022 |
| Command | Description | Example |
|---|---|---|
find |
Search for files and directories | find /home -name notes.txt |
grep |
Search for text inside files | grep "error" logfile.txt |
cat |
Display file contents | cat notes.txt |
less |
View file contents one screen at a time | less notes.txt |
head |
Show the first 10 lines of a file | head notes.txt |
tail |
Show the last 10 lines of a file | tail notes.txt |
tail -f |
Continuously monitor new lines (useful for logs) | tail -f /var/log/syslog |
wc |
Count lines, words, and characters | wc notes.txt |
du |
Show disk usage of files/directories | du -h /home/user |
df |
Show available disk space | df -h |
stat |
Display detailed file information | stat notes.txt |
sort |
Sort lines of text | sort names.txt |
uniq |
Remove duplicate lines (often used with sort) |
sort names.txt | uniq |
cut |
Extract columns or fields from text | cut -d':' -f1 /etc/passwd |
awk |
Advanced text processing and reporting | awk '{print $1}' data.txt |
sed |
Stream editor — modify text in files | sed 's/error/warning/g' logfile.txt |
You can create a new directory using the mkdir command:
$ mkdir folder_name
# creates a new directory called folder_nameUse rmdir to delete empty directories:
$ rmdir Personal
# removes an empty folder named PersonalTo remove files:
$ rm index.html
# deletes the file index.htmlTo remove a directory (and its contents) recursively:
$ rm -r Desktop/Personal
# deletes the directory 'Personal' inside 'Desktop' and all its contentsUse the touch command to create one or more new files:
$ touch answer.txt
# creates a new file named answer.txtYou can create multiple files at once:
$ touch style.css main.js
# creates two files: style.css and main.jsThe echo command prints text in the terminal
$ echo "Who is Morty?"
Who is Morty?
# prints "Who is Morty?" to the terminalYou can also write text to a file:
$ echo "Who is Morty?" > secrets.txt
# creates a file 'secrets.txt' and writes the line inside itTo overwrite or add text to an existing file:
$ echo "Who is Morty?" > ~/logs/2020/1/secrets.txt
# writes the line to the specified file, overwriting its contentsYou can redirect text from one file to another using cat and redirection operators.
< → input redirection
> → output redirection
Example:
$ cat a.txt
AAA
# displays content of a.txt
$ cat b.txt
BBB
# displays content of b.txt
$ cat a.txt > b.txt
# copies content of a.txt into b.txt, overwriting its contentAfter this, both files contain:
AAAIn this example, the content of a.txt is copied to the end of b.txt. The >> operator is used to append data instead of overwriting it.
$ cat a.txt >> b.txt
# the content of a.txt was copied to b.txt
$ cat b.txt
BBB
AAA
# a.txt content was appended to b.txt without overwriting existing dataThe cp (copy-paste) command copies a directory or file. After the command, you must specify:
- The name and path of the source file.
- The name and path of the destination file.
If the file is copied from or to the current directory, you can omit the path.
Examples:
$ cp brothers.html sisters.html
# copied the file brothers.html and named the new copy sisters.html
# both files are in the current folder
$ cp ../docs/brothers.html sisters.html
# specified the path to the source file brothers.html
# the copy is saved in the current folder as sisters.html
$ cp ../docs/brothers.html ../Documents/
# copied brothers.html to the Documents directoryTo copy an entire directory, use the -r flag.
The mv (move) command moves a folder or file and works similarly to the cp command: you specify the file name and the destination path. Always specify the path to the new location.
Examples:
$ mv card.txt ~/
# card.txt moved from the current directory to the home directory
$ mv card.txt /home/logs/2020/
# card.txt moved using an absolute pathThe mv command can also rename a file. To do this, provide the new file name as the second argument.
$ mv my_app.ssh your_app.ssh
# renamed my_app.ssh to your_app.ssh
$ mv /home/logs/2020/card.txt /home/logs/2020/cards.txt
# moved card.txt and renamed it to cards.txt
# absolute path specifiedIf you are already in the directory where you want to move or copy a file, you can omit the source path and just specify the filename.
When you have many log files in a directory and only one of them contains an error, you can use the grep command (Global Regular Expression Print) to search for specific text or patterns across files.
'grep' is a file search utility that finds and displays lines matching a given expression. If no file is specified, it searches across all files in the current directory.
Syntax:
$ grep [Flag(s)] PATTERN [Address]-
PATTERN→ the text you’re looking for (one or more words).- Single word:
Frodo - Multiple words:
"Frodo Baggins"(use quotes)
- Single word:
-
[Address]→ the file or directory path. -
Flag(s)]→ optional arguments that modify the search behavior (e.g., ignore case, recursive search).
| Flag | Meaning | Example |
|---|---|---|
-R |
Search recursively in all files inside a directory | grep -R DELETE ~/logs/2020/1 |
-n |
Show the line number for each match | grep -n DELETE apache_2020-01-01.txt |
-i |
Ignore case sensitivity (uppercase/lowercase) | grep -i delete apache_2020-01-01.txt |
-B |
Show lines before the match | grep -B 2 ERROR system.log |
-A |
Show lines after the match | grep -A 3 ERROR system.log |
-C |
Show lines before and after the match | grep -C 1 ERROR system.log |
-c |
Show only the count of matching lines | grep -c DELETE system.log |
-R — Recursive Search:
The -R flag tells grep to search through all files and subdirectories.
$ grep -R DELETE ~/logs/2020/1-n — Show Line Numbers:
The -n flag displays the line number where each match occurs.
$ grep -n DELETE apache_2020-01-01.txtYou are in your home directory. Go to ~/logs/2020/1.
Find the line number that contains "503 3312" in the file apache_2020-01-01.txt.
$ grep -n "503 3312" apache_2020-01-01.txt1583✅ The string "503 3312" appears on line 1583.
In some cases, it’s important to see not only the matching line but also the surrounding lines — for example, to understand what happened before an error in the logs.
To show adjacent lines, use the flags -B, -A, and -C.
| Flag | Meaning | Description |
|---|---|---|
-B |
before-context | Shows the number of lines before the matching line |
-A |
after-context | Shows the number of lines after the matching line |
-C |
context | Shows the number of lines before and after the matching line |
Example:
$ grep -C 1 DELETE ~/logs/2020/1/apache_2020-01-01.txtThis command shows the line containing DELETE plus one line above and below it.
Use the -c flag to return only the number of lines that match your search term:
Example:
$ grep -c DELETE ~/logs/2020/1/apache_2020-01-01.txt| Symbol | Description | Example |
|---|---|---|
[] |
Match one of several characters | grep -i N[ua]m1 Log1.txt → matches Num1, Nam1, num1, nam1 |
. |
Matches any single character | grep "204 3.96" apache_2020-01-01.txt |
^ |
Matches the beginning of a line | grep "^Start" text.txt → shows lines starting with “Start” |
$ |
Matches the end of a line | grep "End$" text.txt → shows lines ending with “End” |
^$ |
Matches empty lines | grep ^$ text.txt → finds blank lines |
$ grep ERROR /test1/test2/test_Logs/Log1.txt > errors.txtAll lines containing the word “ERROR” are saved into errors.txt.
Sometimes the term DELETE appears with different cases or abbreviations like DEL. You can handle this with:
-
-i→ ignores uppercase/lowercase -
*(asterisk) → matches any number of characters
Example:
$ grep -i DEL* ~/logs/2020/1/apache_2020-01-31.txt| 🔹 Command / Shortcut | 🧩 Description | 💻 Example / Notes |
|---|---|---|
| ↑ / ↓ (Arrow keys) | Browse through previous commands in your command history. | Press ↑ to recall the last command, ↑↑ twice for the one before it. |
| Ctrl + A | Move cursor to the beginning of the command line. | Great for quickly editing the start of a long command. |
| Ctrl + E | Move cursor to the end of the command line. | Jump to the end instantly. |
| Ctrl + U | Clear the entire command line. | Deletes everything currently typed. |
| Ctrl + C | Interrupt a running process. | Use when a command hangs or runs too long. |
mv *.txt ~/Desktop |
Move all .txt files to the Desktop using wildcards. |
Moves every text file from current directory. |
cp j*.txt ~ |
Copy all files starting with “j” and ending in .txt. |
Copies jodorowsky_film.txt, jodorowsky_comics.txt, etc. |
history |
Show your command history. | Lists all commands used in current session. |
history > commands.log |
Save command history to a file. | Stores full history in commands.log. |
SQL (Structured Query Language) is a programming language designed to manage and manipulate data in relational databases.
| Term | Definition |
|---|---|
| Database | A structured repository of information. |
| Entity | A group of objects that share common characteristics. |
| Relational Database | A type of database where entities are tables and objects are rows. |
| DBMS (Database Management System) | Software that allows you to create, manage, and edit databases and tables. |
| Table | A collection of rows and columns representing structured data. |
| Field | A column in a table that defines a specific attribute and has a name and data type. |
| Record | A row in a table containing data about one object. |
| Cell | The intersection of a row and column. |
| Primary Key | A unique field (or group of fields) used to identify records. It must not contain duplicates or NULL values. |
| Query | A structured SQL command that specifies what data to retrieve and how to process it. |
-- Single-line comment
/* Multi-line
comment */Select specific columns:
SELECT column_name_1, column_name_2, column_name_3
FROM table_name;Select all columns:
SELECT *
FROM table_name;Select with condition:
SELECT column_name_1, column_name_2
FROM table_name
WHERE condition;Select rows where a value is between two values:
SELECT *
FROM table_name
WHERE field_1 BETWEEN value_1 AND value_2;Select rows where values are in a specific list:
SELECT *
FROM table_name
WHERE column_name IN ('value_1', 'value_2', 'value_3');SELECT
COUNT(*) AS total_rows,
COUNT(column) AS non_null_rows,
COUNT(DISTINCT column) AS unique_values,
SUM(column) AS total_sum,
AVG(column) AS average_value,
MIN(column) AS min_value,
MAX(column) AS max_value
FROM table_name;SELECT CAST(column_name AS data_type)
-- or
SELECT column_name :: data_typeGroup Data:
SELECT field_1, field_2, AGGREGATE_FUNCTION(field) AS result
FROM table_name
WHERE condition
GROUP BY field_1, field_2;Order results:
SELECT field_1, field_2, AGGREGATE_FUNCTION(field) AS result
FROM table_name
WHERE condition
GROUP BY field_1, field_2
ORDER BY field_1 DESC, field_2 ASC
LIMIT n;Insert data:
INSERT INTO table_name (column_1, column_2, column_3)
VALUES (value_1, value_2, value_3);Update data:
UPDATE table_name
SET column_name = new_value
WHERE condition;Delete data:
DELETE FROM table_name
WHERE condition;| Command | Description |
|---|---|
SELECT |
Retrieves data from a table. |
WHERE |
Filters data based on a condition. |
BETWEEN |
Selects data between two values. |
IN |
Filters data within a specific list. |
COUNT, SUM, AVG, MIN, MAX |
Aggregate functions to perform calculations. |
GROUP BY |
Groups data by one or more fields. |
ORDER BY |
Sorts data ascending (ASC) or descending (DESC). |
INSERT INTO |
Adds new data into a table. |
UPDATE |
Modifies existing records. |
DELETE |
Removes records from a table. |
CAST |
Converts a value to a different data type. |
Use LIMIT n to restrict the number of rows returned, especially when testing queries on large datasets.
A foreign key (FK) is a column in one table that contains values from another table — it links the two.
| Relationship Type | Description | Example |
|---|---|---|
| One-to-One (1:1) | Each row in one table is linked to exactly one row in another. | Employee → Payroll_Info (each employee has one payroll record). |
| One-to-Many (1:N) | One row in a table corresponds to multiple rows in another. | Author → Books (an author can write many books, but each book has one author). |
| Many-to-Many (N:N) | Multiple rows in one table relate to multiple rows in another. | Requires a junction table combining both primary keys (e.g., students_courses). |
ER diagrams visually represent how tables and their relationships are structured in a database.
Elements:
- Tables: Shown as rectangles divided into two parts:
- Upper part: table name
- Lower part: list of fields with keys indicated (
PK= Primary Key,FK= Foreign Key)
- Relationships: Lines connecting tables, with symbols indicating cardinality (1:1, 1:N, N:N).
Find records with missing or empty fields using IS NULL or IS NOT NULL.
-- Rows with empty values
SELECT *
FROM table_name
WHERE column_name IS NULL;
-- Rows with non-empty values
SELECT *
FROM table_name
WHERE column_name IS NOT NULL;| Operator | Meaning |
|---|---|
= |
Equal to |
!= |
Not equal to |
> |
Greater than |
< |
Less than |
>= |
Greater than or equal to |
<= |
Less than or equal to |
| Operator | Description |
|---|---|
AND |
Both conditions must be true |
OR |
One or both conditions can be true |
NOT |
The condition must be false |
| Operator | Description |
|---|---|
BETWEEN |
Selects values within a specific range (inclusive) |
IN |
Filters rows that match any value from a list |
LIKE |
Searches for a pattern using wildcards |
Returns only the rows that have matching values in both tables (intersection).
SELECT
table1.field_1,
table1.field_2,
table2.field_n
FROM table1
INNER JOIN table2 ON table2.field_1 = table1.field_2;Key Points:
- Table order doesn’t affect the result.
- Includes only rows that meet the join condition.
- Be careful with duplicates in 1:N relationships.
Selects all rows from the left table and the matching rows from the right table.
Non-matching rows from the right table are filled with NULL.
SELECT
table1.field_1,
table1.field_2,
table2.field_n
FROM table1
LEFT JOIN table2 ON table2.field_1 = table1.field_2;Key Points:
- Keeps all rows from the left table.
- Missing matches from the right table show as NULL.
- Useful for finding records that exist in one table but not another.
Selects all rows from the right table and the matching rows from the left table.
Non-matching rows from the left table are filled with NULL.
SELECT
table1.field_1,
table1.field_2,
table2.field_n
FROM table1
RIGHT JOIN table2 ON table1.field_1 = table2.field_2;Key Points:
- Keeps all rows from the right table.
- Works similarly to
LEFT JOIN, just mirrored. - Less common but useful in some scenarios.
You can join more than two tables by chaining multiple JOIN statements.
SELECT
table1.field_1,
table2.field_2,
table3.field_3
FROM table1
INNER JOIN table2 ON table1.id = table2.table1_id
INNER JOIN table3 ON table2.id = table3.table2_id;- Each new JOIN builds on the previous one.
- You can mix different join types (INNER, LEFT, RIGHT).
- The order of joins can affect results.
- Always double-check each ON condition.
Example:
SELECT
customers.name,
orders.order_date,
products.product_name
FROM customers
INNER JOIN orders ON customers.id = orders.customer_id
INNER JOIN order_items ON orders.id = order_items.order_id
INNER JOIN products ON order_items.product_id = products.id;| Concept | Description |
|---|---|
| Foreign Key | A column linking two tables. |
| ER Diagram | Visual map of tables and relationships. |
| IS NULL / IS NOT NULL | Filters empty or non-empty data. |
| Comparison Operators | =, !=, >, <, >=, <= |
| Logical Operators | AND, OR, NOT |
| JOINs | Combine data from related tables. |
| LEFT JOIN | Keep all records from the left table. |
| RIGHT JOIN | Keep all records from the right table. |
| Multiple JOINs | Combine three or more tables. |
SSH (Secure Shell) is a network protocol used to securely access another computer remotely. It encrypts all communication between client and server.
Remote access to servers or devices.
Executing commands securely.
Transferring files (scp, sftp).
Tunneling other network traffic.
ssh user@server_ip- Private key stays on the client.
- Public key goes on the server.
They provide secure passwordless authentication.
SSH is very secure when properly configured, but risks include:
- Weak passwords → use SSH keys instead.
- Outdated SSH versions → keep OpenSSH updated.
- Not verifying host fingerprints → risk of MITM attacks.
- Exposed port 22 → use a non-standard port or firewall.
- Stolen private keys → protect with passphrases.
| Setup | Security Level |
|---|---|
| Password login | Medium |
| Key-based authentication | Strong |
| Outdated/misconfigured SSH | Weak |
- Default SSH port: TCP 22
- Brute-force attacks → disable password logins.
- Port scanning → change default port or restrict via firewall.
- Outdated versions → keep updated.
- Use key-based authentication.
- Change default port.
- Limit IP access.
- Use tools like Fail2Ban or UFW.
- The client does not open permanent ports.
- It uses a temporary ephemeral port for outbound connection (e.g., Client:54321 → Server:22).
- The port closes automatically when the session ends.
Ports open locally only when port forwarding is used.
| Mode | Description | Open Port |
|---|---|---|
-L |
Local forwarding | Opens local port (localhost only) |
-R |
Remote forwarding | Opens port on remote server |
-D |
Dynamic forwarding | Opens local SOCKS proxy port |
To disconnect cleanly:
exitIf the session freezes:
~.If the terminal is closed, the SSH session ends immediately.
Best practice: always use exit.
Core cybersecurity principles learned through TryHackMe and self-study:
- Understanding security principles, governance, and regulation.
- The Cyber Kill Chain model for analyzing attack stages.
- Fundamental defensive practices (updates, authentication, network segmentation).
This section covers the fundamentals of Python. It provides a beginner-friendly overview to help build the foundation needed for future test automation.
Python is a high-level, interpreted programming language that is easy to read and write.
It is widely used for automation, software testing, data analysis, web development, and more.
- Simple and readable syntax (easy for beginners)
- Large ecosystem of libraries and frameworks for testing (e.g.,
pytest,unittest) - Cross-platform: works on Windows, macOS, Linux
You can run Python in different ways:
| Method | Description |
|---|---|
| Python Interpreter | Run Python directly in the terminal or command prompt |
Python Script File .py |
Write code in a file and execute it |
| IDE (e.g., PyCharm, VS Code) | Allows writing, running, and debugging Python projects |
python3 hello.pyIndentation is mandatory in Python. It defines code blocks – not {} brackets like other languages.
if 5 > 3:
print("Python uses indentation!")Variable, variable, and VARIABLE are all different.
Used to explain code and make it easier to understand.
# This is a single-line comment"""
This is a multi-line
comment in Python
"""A variable stores data that can change during program execution. You do not need to declare the type — Python detects it automatically.
name = "Camilo"
age = 25Rules for variable names:
- Must start with a letter or _
- Cannot start with a number
- Cannot contain spaces or symbols like @, $, %
- Case-sensitive
A data type defines the kind of value a variable holds.
Python automatically detects the type of data assigned to a variable — this is called dynamic typing.
| Data Type | Example | Description |
|---|---|---|
int (integer) |
10 |
Whole numbers |
float (decimal) |
10.5 |
Numbers with decimals |
str (string) |
"Hello" |
Text |
bool (boolean) |
True, False |
Logical values |
age = 25 # int
price = 9.99 # float
name = "Camilo" # string
is_testing = True # boolprint("Hello, Python!")name = input("Enter your name: ")
print("Hello, " + name)Note: input() always returns a string.
| Operator | Example | Description |
|---|---|---|
+ |
2 + 3 |
Addition |
- |
5 - 2 |
Subtraction |
* |
4 * 3 |
Multiplication |
/ |
8 / 2 |
Division (always returns float) |
// |
8 // 2 |
Floor division (no decimals) |
% |
7 % 3 |
Modulo (remainder) |
** |
2 ** 3 |
Exponent (power) |
Python includes two common number types:
| Type | Description | Example |
|---|---|---|
int |
Whole numbers (no decimals) | 10, -3, 0 |
float |
Numbers with decimals | 10.5, 0.75, -3.14 |
Operations apply differently:
a = 5 # int
b = 2.5 # float
print(a + b) # 7.5 (result is float)A string stores text. It must be wrapped in quotes.
text1 = "Hello"
text2 = 'Python'Strings can be combined (concatenated):
name = "Camilo"
print("Hello, " + name)You can also get the lenght of a string:
len("Python") # 6Indexing and slicing let you access elements or sub-parts of sequences: lists, tuples, strings.
- Python uses zero-based indexing: the first element is at index 0.
- Negative indices start from the end: -1 is the last element.
fruits = ["apple", "banana", "orange"]
print(fruits[0]) # apple
print(fruits[-1]) # orangeStrings use the same indexing rules:
text = "Python"
print(text[0]) # 'P'
print(text[-2]) # 'o'- Syntax: sequence[start:stop:step]
- start is inclusive, stop is exclusive.
- step is optional (default 1).
- Omit start to begin at 0, omit stop to go to the end.
numbers = [0,1,2,3,4,5]
print(numbers[1:4]) # [1, 2, 3] (elements 1,2,3)
print(numbers[:3]) # [0, 1, 2] (start to index 2)
print(numbers[3:]) # [3, 4, 5] (index 3 to end)
print(numbers[::2]) # [0, 2, 4] (every 2nd element)- Get last N elements: seq[-N:]
- Reverse a sequence: seq[::-1]
print(numbers[-3:]) # last 3 elements -> [3,4,5]
print(text[::-1]) # reverse string -> "nohtyP"Represents True or False values. Used a lot in automation for conditions and test validations.
is_valid = True
print(is_valid) # TrueBooleans often come from comparisons:
print(4 > 2) # True
print(3 == 5) # FalseA list stores multiple values in one variable. Lists are ordered, changeable, and can contain different data types.
fruits = ["apple", "banana", "orange"]
print(fruits[1]) # bananaYou can modify a list:
fruits.append("kiwi")A tuple is similar to a list but cannot be changed (immutable).
colors = ("red", "green", "blue")Use tuples when you want to store constant values.
A dictionary stores data as key–value pairs, like a real dictionary.
person = {
"name": "Camilo",
"age": 25,
"country": "Australia"
}Access values by key:
print(person["name"]) # CamiloLoops let you repeat a block of code multiple times. Python has two main loop types: for and while.
- Iterates over items of a sequence (list, tuple, string) or over a range of numbers.
- Common when you know the number of iterations or when you want to process every item in a collection.
# Iterate directly over a list
fruits = ["apple", "banana", "orange"]
for fruit in fruits:
print(fruit)
# Iterate using range() — numbers from 0 to 2
for i in range(3):
print(i) # 0, 1, 2
# Iterate with indices
for i in range(len(fruits)):
print(i, fruits[i])- Repeats as long as a condition is True.
- Useful when the number of iterations depends on runtime conditions.
count = 0
while count < 3:
print("count =", count)
count += 1break— immediately exit the loop.continue— skip the rest of the current iteration and continue with the next one.- You can combine conditions to control behavior inside loops.
for i in range(5):
if i == 2:
continue # skip printing 2
if i == 4:
break # stop loop when i == 4
print(i) # prints 0, 1, 3You can convert a value from one type to another:
age = "25"
age = int(age) # convert string to int
print(type(age)) # <class 'int'>Common conversions:
int()float()str()bool()
Functions are reusable blocks of code that help you avoid repetition and make your programs easier to read, organize, and maintain. This section covers how to define functions, pass arguments, return values, and test functions using assert.
A function is a named block of code that performs a specific task.
Python has many built-in functions (e.g., print()), but you can also create your own.
- Avoid repeating the same code
- Organize logic into reusable components
- Make your code easier to test
To create a function, use the keyword def followed by the function name and parentheses.
Example:
def hello():
print("Hello!")- Use lowercase letters
- Use underscores to separate words
- Example: say_hello, calculate_total The function body is indented with 4 spaces:
def hello():
print("Hello!") # function bodyTo run a function, call it by writing its name followed by parentheses:
hello()A function can accept parameters — placeholders for data the function needs.
Example:
def hello(name):
print(name + ", hello!")When calling the function, pass the argument:
hello("Andrea")
# Output: Andrea, hello!def greet(name, task):
print(name + ", hello! It's time to " + task)
greet("Daniel", "fix bugs")
greet("Jennifer", "write test cases")
greet("Gabriel", "lift team morale")Order matters:
- First argument → first parameter
- Second argument → second parameter
Functions can return values to be used later in the code.
Use the keyword return.
Example:
def add(a, b):
return a + b
result = add(3, 5)
print(result) # 8calories = {
"Hamburger": 600,
"Cheeseburger": 750,
"Veggie Burger": 400,
"Vegan Burger": 350,
"Fries": 230,
"Salad": 15,
"Iced Tea": 70,
"Lemonade": 90
}
def calories_counter(item_a, item_b, item_c):
return calories[item_a] + calories[item_b] + calories[item_c]
print(calories_counter("Hamburger", "Cheeseburger", "Iced Tea"))
# Output: 1240Explanation:
- The function receives three dishes as parameters
- Uses return to add their calorie values
- The final number is printed when the function is called
assert is used to verify that a condition is True.
If it's not True, Python raises an AssertionError and stops the program.
Example:
assert 5 + 6 == 11 # Test passesIf a test fails:
assert 5 == 4Python shows:
AssertionError
+5
-4- Helps automate tests
- Immediately shows mismatched results
- Prevents the program from continuing with incorrect logic
def test_deposit_more_than_zero():
deposit = get_user_deposit()
assert deposit > 0Other valid comparison operators with assert:
==(equal)!=(not equal)>(greater than)<(less than)>=,<=
Pytest is a testing framework for Python that makes it easy to write, run, and manage automated tests.
This section covers how Pytest works, how to install it, how to run tests, and how it is used together with the requests library for API testing.
In Pytest, a test is a function whose name starts with the prefix test_.
Important rules:
- Test function names must start with
test - Pytest is case-sensitive
- ✅
test_login - ❌
Test_login
- ✅
Example:
def test_sum():
assert 2 + 3 == 5There are two ways to install Pytest.
pip install pytestIf pip does not work, try:
pip3 install pytestpip is Python's built-on package manager used to install libraries.
- Open your project in PyCharm
- Open the Python Packages tab (bottom panel)
- Search for pytest
- Click Install
Run all tests in the project:
pytestRun tests from a specific file:
pytest calc_test.pyRun all tests:
- Go to Run → Edit Configurations
- Click + Add New Configuration
- Select Python tests → pytest
- Choose Custom as the target
- Click Apply → OK
- Click the green
▶️ button to run tests
Run tests from a specific file:
- Go to Run → Edit Configurations
- Add Python tests → pytest
- Leave Script path selected
- Choose the test file
- Click Apply → OK
- Run using the green
▶️ button
Running a single test from the editor
- After installing Pytest, a green arrow appears next to test functions.
- Click it to run that test only.
The requests library is used to send HTTP requests (GET, POST, etc.).
Installation Install requests using:
pip install requestsOr via Python PAckages in PyCharm.
Step 1: Create configuration.py Store base URLs and paths:
URL_SERVICE = "https://example.com"
DOC_PATH = "/docs/"Step 2: Create sender_stand_request.py
import configuration
import requests
def get_docs():
return requests.get(configuration.URL_SERVICE + configuration.DOC_PATH)
response = get_docs()
print(response.status_code)| Attribute | Purpose |
|---|---|
status_code |
HTTP response code |
headers |
Response headers |
ok |
True if status code is 2xx or 3xx |
url |
Request URL |
request |
Request method |
text |
Response body as text |
json() |
Converts response body to dictionary |
Step 1: Add path to configuration.py
CREATE_USER_PATH = "/api/v1/users/"Step 2: Create data.py
headers = {
"Content-Type": "application/json"
}
user_body = {
"firstName": "Andrea",
"phone": "+11234567890",
"address": "123 Elm Street, Hilltop"
}Step 3: Send POST request
import configuration
import requests
import data
def post_new_user(body):
return requests.post(
configuration.URL_SERVICE + configuration.CREATE_USER_PATH,
json=body,
headers=data.headers
)
response = post_new_user(data.user_body)
print(response.status_code)To write clean and reliable tests, follow these three rules:
✅ One test → one assertion
- Each test should verify one condition only.
✅ Independent test data
- Tests should not depend on shared or modified data.
✅ Independent tests
- Each test must be able to run alone, in any order.
This Python cheat sheet was created by Jack Rhysider, the host of Darknet Diaries, and is shared here for educational and personal learning purposes.
📝 Credit: Original creator — Jack Rhysider
📄 Source: Python Cheat Sheet (Darknet Diaries)
⚖️ Note: All rights belong to the original author. This resource is included here solely for study and reference.