Introduction to Python
A beginner-friendly look at Python, why it matters, and how it shows up in real security workflows.
Python is one of the most popular and beginner friendly programming languages in the world. For starters, a vast majority of pentesting tools you will find on GitHub are written in Python. Whether you're hoping to automate boring tasks, scrape and analyze data, or start building and customizing your own tools, Python is a great place to start. It is especially helpful for those who have never touched a programming language and want to learn because it is very beginner friendly. What exactly is it, though?
Come on. I'll show you.
This will be a longer post, so if you'd like to jump ahead:
- Setting up Python
- Syntax & Data Types
- Integers
- Strings
- Booleans
- Conditional Logic
- Loops
- Accepting user input
- Functions
- Lists
- Dictionaries
- Where to go from here
[+] - What is python? - [+]
Python is a high-level programming language, which means it is written in a way that can be easily read and understood by humans. Some other examples of high-level programming include JavaScript, Ruby, and PHP. Learning to program is quite literally like learning a new language. You can look up syntax and commands, but you will need to practice.
As someone with personal experience, Python was a really easy language to catch on to, at least as far as syntax. The main challenge is learning to think in a Pythonic, or object oriented way. One benefit of its popularity is the massive community. You can find tutorials on YouTube or TikTok, free courses and writeups, and even one on one training. I got started by enrolling in the free CS50: Introduction to Programming with Python. The lectures walk you through each topic step by step in a way that not only teaches the syntax, but also explains why we do it this way. Each week also includes homework assignments that give you a chance for some hands on practice with what you learned that week.
I am not affiliated with Harvard University or any other resource I list here. These are just resources that I personally found helpful. This guide is meant for those with little to no Python or programming experience. We will start by building up your knowledge base step by step. You will write your first Python program, and by the end of the post, hopefully you will understand how variables, loops, functions, and Pythonic thinking all fit together.
Without further ado, lets get started!
SETTING UP PYTHON
Before we start writing code, we need to make sure Python is installed on your computer. Linux and Mac users may already have Python installed. To check, open your terminal (Mac/Linux) or Command Prompt (Windows) and type this command:
python --version
OR
python3 --version
If you see something like Python 3.11.5, you're all set. If not, it is pretty simple to install. Windows and Mac users can download and install Python here. When running the installer, make sure you check the box that says Add Python to PATH. This is important as it will allow you to run Python code system wide from any folder or location. If you are using Debian/Ubuntu based Linux distributions, the simplest way to install Python is to type the following commands into your terminal.
sudo apt install python3
sudo apt install python3-pip
Python files will end in the extension .py. We can create a Python file in literally any text editor, but here are some of the more popular ones.
The most common professional grade IDE (Integrated Development Environment) is VSCode by Microsoft. If you prefer open source programs, you can check out VSCodium, which is identical to VSCode but without the telemetry. This is a good option if you plan to use other languages besides just Python. VSCode allows you to install extensions for JavaScript, C++, and most other languages. One thing I like about VSCode is that it highlights parts of the code based on formatting, like all functions being blue for example. If you choose this option, be sure to install the Python extension inside of VSCode.
Another option is PyCharm. This is an IDE that is specifically designed for Python, though I think JetBrains makes IDEs for other languages. All of these options are Integrated Development Environments, which means you can write the code and run the code in a terminal, as well as organize all your files and scripts, in one program.
If you don't like any of those options, you can use any text editor of your choice. You will need to create a folder for your files and save the document with the .py extension. To run your scripts, you will need to open a terminal or command prompt in the same folder as your script. To run your script, simply type:
python file_name.py
I am also pretty fond of the Sublime text editor. Any option you choose will work just as well.
If you want to skip all that and just get started, you can find a browser based Python compiler here.
SYNTAX & DATA TYPES
Before we start coding, we need to understand the building blocks of Python, how Python stores information, and how to write code that Python can understand. Python is known for its clean, easily readable syntax, which means no curly brackets ({}) or semicolons (;) are needed. Something to keep in mind regarding formatting and syntax is that indentation matters. Code blocks are grouped by indentation, usually the Tab key. If you do not properly indent, Python will give you an IndentationError when you try running your script.
IndentationError: expected an indented block
A variable is the name for a piece of data. We've all seen the algebra equations where you solve for x. Well, this is like that. To create a variable, you will need to list the name of the variable followed by an equals sign (=), then the value you'd like assigned to the variable on the right. One thing to note here is that a single = is how we assign values to a variable. If we want to compare whether two values or variables are equal, we need to use a double equals (==). A pound sign or hashtag (#) indicates a comment in the code. Anything after the # will only be visible in the code. It will not render once the code is run.
name = "Alice" # This is a comment
age = 25
height = 5.7
You can think of variables as labeled boxes holding specific values that we can call on later. Variables can be anything you want. In the code above, we have name, age, and height, but we could easily have called them banana, raincloud, and ocean, though that would not be very descriptive. It is good practice to name variables descriptively, both for your sake and for the sake of anyone reading your code.
In the above code snippet, notice that we have a few different types of information here. We have the string (str) "Alice", the integer (int) 25, and the decimal, or float (float), value 5.7. These pieces of data will be handled differently, so it is important to know the most common data types in Python.
The most common data types you will encounter are as follows:
str(string): a sequence of characters, like"alice"or"123"int(integer): whole numbers, including positive, negative, & zerofloat: decimal or fractional numbersbool: a boolean value, which is always eitherTrueorFalse
Python is comprised of a series of functions, some of which are included with Python and others you can define for yourself. Functions perform some operation or series of steps on a variable. You can check the type of any value using the type() function:
print(type(name))
print(type(age))
Output:
<class 'str'>
<class 'int'>
Functions in Python can be layered or stacked inside of one another. In the example above, we can see the type() function inside of the print() function. Python interprets these kinds of functions from the inside out, so this code will print whatever the result of type(name) is.
This all felt super overwhelming for me at first as well. Don't worry. I got you BooBoo!
WORKING WITH INTEGERS
x = 5 + 5
y = 10 - 5
z = 20 / 10
a = 5 * 2
print(x)
print(y * 2)
print(x + y + z)
Integers in Python work similarly to basic algebra. Like the calculator on your phone or PC, Python uses the basic addition (+), subtraction (-), multiplication (*), and division (/) signs for doing math. A quick note on division in Python: a true division operator (/) may result in a float, which just means it is not a whole number. If you want to truncate the decimal part, you would use the floor division operator (//).
Looking at the code above, we are assigning whatever the value of 5 + 5 is to the variable x, the value of 10 - 5 to y, and so on. Python usually interprets from the top down, so once the values of x, y, z, and a are assigned, the value of x is printed, or displayed on the screen. One thing to note is that you can use multipliers with variables as well. Here, we are taking the value of y and multiplying it by 2.
We can also make equations with variables. The last line prints the value of x + y + z.
We can't cover everything we can do with integers in this post, but we can do a lot more than just basic arithmetic. Let's look at some other operations we can do with integers.
# A FEW OTHER MATH OPERATORS
a % b # Returns the remainder of a / b
int(3.5) # Turns 3.5 into an integer (3)
a ** b # Returns the result of a to the power of b
abs(-a) # Returns the absolute value of a
round(number, 2) # Rounds number to 2 decimal places
x > y # Returns True if x is greater than y
x == y # Returns True if x is equal to y
x != y # Returns True if x and y are not equal
# CONVERSION FUNCTIONS
int(x) # Converts x to an integer
str(x) # Converts x to a string
bin(x) # Converts x to a binary string
hex(x) # Converts x to a hexadecimal string
sum(iterable, 0) # Sum of items in an iterable starting with 0
WORKING WITH STRINGS
One of the most common data types you will work with in Python is str(). A string is a series of characters. This can be any letter, number, or symbol you'd like so long as the string is enclosed with quotes. There are a lot of ways to manipulate strings in Python.
first = "Alison"
last = "Wonderland"
age = 25
multi = """This is
a multi-line string."""
hah = "haha"
print(hah * 3)
print(first + " " + last)
print("Your age is " + str(age))
print(multi)
print(f"My name is {first} and I am {age} years old.")
The first print function takes the value of the variable hah and prints it 3 times. We can also quote a string directly in the print function, so print("string" * 3) would display stringstringstring.
When we use + with strings in a print() function, this is called concatenation, which is a fancy way of saying "putting stuff together." This function prints the value of first, followed by a space, followed by the value of last.
It is important to note that you cannot concatenate different data types, so if you wanted to print a string followed by an integer, you'd have to convert the integer to a string using str().
The last print() function is called an f-string. It is just an easy way of formatting the output of your print() function. To do this, add an f before the quotes. Once you do that, you can add any variable by putting it inside curly brackets.
[+] - MANIPULATING STRINGS - [+]
There's way too much we can do with strings in Python to list here, so lets go over some basics.
string = " Hello, World! "
print(string.strip()) # Remove space from start & end of line
print(string.lower()) # Converts to lowercase
print(string.upper()) # Converts to uppercase
print(string.startswith("H")) # True if string begins with "H"
print(string.endswith("!")) # True if string ends with "!"
print(string.replace("Hello", "Goodbye"))
We can do a lot of fun things like join two strings together, separate a string, assign different parts to multiple variables, replace characters, and basically anything else you can think of. Let's look at a few more examples.
text = "apple, banana, cherry, 25"
words = text.split(",")
joined = "-".join(words)
print(words)
print(joined)
print(len(text))
Output:
['apple', ' banana', ' cherry', ' 25']
apple- banana- cherry- 25
25
BOOLEANS
In Python, booleans are a fundamental data type used to represent the truth of a statement. They form the backbone of decision-making in code, helping to control the flow of programs with conditions, comparisons, and logical operations. A boolean (bool) will only ever return either True or False.
x = 5 > 3
y = 10 < 7
z = 5 == 5
print(x)
print(y)
print(z)
a = 3
b = 9
c = 20
print(a < b)
print(a == c)
print(a != b)
In the code above, we start by creating a boolean and assigning it to the x variable. If we print that variable by itself, the output will be the word True. Understanding how booleans work, and how Python interprets different values as true or false, is essential for writing effective and intelligent code.
CONDITIONAL LOGIC
Conditional logic allows your Python programs to make decisions. Using statements like if, elif, and else, you can write code that responds differently depending on whether certain conditions are true or false.
temp = 75
if temp > 70:
print("It's warm outside!")
This is the basic if/then statement. First, we assign the value 75 to the temp variable. If that variable is greater than 70, which in this case is true, this code will print the statement "It's warm outside!".
Conditional logic becomes even more powerful when combined with comparison and logical operators. You can evaluate multiple conditions at once using and, or, and not.
age = 25
has_ticket = True
if age >= 18 and has_ticket:
print("Welcome to the concert!")
else:
print("Sorry, you can't enter.")
is_raining = False
has_umbrella = False
if is_raining or has_umbrella:
print("You'll stay dry.")
else:
print("Hope the weather holds!")
We can use this format to check multiple conditions in a clean, readable way using the keyword elif.
score = 72
if score >= 90:
print("Grade: A")
elif score >= 80:
print("Grade: B")
elif score >= 70:
print("Grade: C")
else:
print("Keep practicing!")
# We can write this same code another way
if 70 <= score < 80:
print("Grade: C")
We can also nest conditions inside one another, though this can get pretty confusing.
username = "admin"
password = "1234"
if username == "admin":
if password == "1234":
print("Access granted.")
else:
print("Wrong password")
else:
print("Invalid user.")
[+] - COMMON MISTAKES IN CONDITIONAL LOGIC - [+]
When learning conditional logic, there are a few key issues where beginners often stumble, like accidentally using = instead of ==, forgetting colons at the end of if or else lines, or misusing indentation.
# Assigns the value 10 to the variable x
x = 10
if x = 5:
print("This will cause a syntax error.")
# Compares the value of x with 5
if x == 5:
print("This will not print because x is not equal to 5, but the code will run.")
Best practices:
- Keep conditions clean and readable
- Use parentheses for clarity when combining conditions
- Use descriptive variable names to make logic self-explanatory
- When in doubt, break complex conditions into multiple steps
if (age > 18 and has_id) or is_vip:
print("Access granted")
LOOPS: REPETITION WITH PURPOSE
While conditional logic allows your code to make decisions, loops let it repeat actions. Loops are essential for automating monotonous or repetitive tasks, whether you're processing a list of items, counting down a timer, or prompting a user until they give a valid answer.
Python offers two primary loop types: for loops for iterating over sequences, and while loops for repeating a thing until a condition is no longer true.
# Basic 'for' loop
for i in range(5):
print("Loop number", i)
# Output
# Loop number 0
# Loop number 1
# Loop number 2
# Loop number 3
# Loop number 4
# Basic 'while' loop
count = 3
while count > 0:
print("Counting down:", count)
count -= 1
# Output
# Counting down: 3
# Counting down: 2
# Counting down: 1
A for loop is used when you know the number of iterations or are iterating through a sentence or string. A while loop is used when the end condition is not known.
# count += 1
count = count + 1
# count -= 1
count = count - 1
Let's look at a few more tools we can use with loops.
# Continue - skips to next loop iteration
i = 0
while i < 10:
i += 1
if i % 2 == 0:
continue
print("Odd number:", i)
# Break - exits the loop entirely
while True:
command = input("Type 'exit' to quit: ")
if command == "exit":
print("Exiting loop.")
break
print("You typed:", command)
# Pass - placeholder, 'do nothing for now'
x = 0
while x < 5:
if x == 2:
pass
print("x is:", x)
x += 1
# Nested while loops
i = 1
while i <= 3:
j = 1
while j <= 2:
print(f"Outer loop: {i}, Inner loop: {j}")
j += 1
i += 1
There is a lot we can do with loops, which is what makes Python such an amazing tool for automation.
ACCEPTING USER INPUT
So far, we've written Python programs that run from start to finish without any user interaction, but real programs rarely work that way. Enter the input() function. This is one of the first tools for making interactive code.
# Basic input function; assign input value to 'name'
name = input("What is your name?: ")
print(name)
# Using input function in if statements
# input() function is a string by default; must convert to int to use as int
age = int(input("How old are you? "))
if age >= 18:
print("You're an adult.")
else:
print("You're not an adult yet.")
# Repeat until secret word is guessed
secret = "python"
guess = ""
while guess != secret:
guess = input("Guess the secret word: ")
print("You guessed it!")
# Basic menu code
while True:
print("\nMenu:")
print("1. Say hello")
print("2. Say goodbye")
print("3. Quit")
choice = input("Choose an option (1-3): ")
if choice == "1":
print("Hello!")
elif choice == "2":
print("Goodbye!")
elif choice == "3":
print("Exiting the program...")
break
else:
print("Invalid choice. Try again.")
For more information about the input() function, check out this link.
INTRO TO FUNCTIONS
As your Python programs grow, you'll notice some code starts to repeat or becomes too long to manage easily. That's where functions come in. A function is a reusable block of code that performs a specific task. Instead of rewriting the same instructions over and over, you can define a function once and use it whenever you need it. Functions make your code cleaner, more organized, and much easier to read and debug. Python has many built-in functions that we've already used like print() and len(), but you can also write your own functions.
You will define your functions at the top of your Python code. You can give the function any name you'd like, though you should probably use descriptive names to make things easier for both you and anyone else reading through your code. To define a function, we will start with the keyword def, followed by the name of the function. Don't forget to indent all of the code you want to include inside of your function.
def greet():
print("Hello there!")
greet()
# OUTPUT
# Hello there!
In the code above, we have defined a very basic function, greet(). This function is pretty simple. When it is called later in the code, it will print the string "Hello there!". Nothing you put inside that function will happen until the function is called later in code.
def greet_user(name):
print(f"Hello, {name}!")
greet_user("Thea")
greet_user("Alex")
Functions can also return values:
def add_numbers(a, b):
return a + b
result = add_numbers(5, 3)
print(result)
You can also assign default parameter values:
def greet_with_default(name="friend"):
print(f"Hello, {name}!")
greet_with_default()
greet_with_default("Thea")
Once you start using functions consistently, your programs get much easier to expand and troubleshoot.
LISTS
When you're learning Python, two of the most useful tools you'll encounter are lists and dictionaries. Lists let you store items in a specific order, like a shopping list or a playlist, while dictionaries store data in key-value pairs. Understanding these two data types will make your programs more organized, flexible, and powerful.
[+] - LISTS - [+]
fruits = ["apple", "banana", "cherry"]
print(fruits)
Lists are ordered collections of items. You can access list items by index position.
fruits = ["apple", "banana", "cherry"]
print(fruits[0])
print(fruits[1])
print(fruits[-1])
You can also update lists by adding or removing items.
fruits.append("orange")
fruits.remove("banana")
print(fruits)
Looping through a list is also very common:
for fruit in fruits:
print(fruit)
Lists are especially useful when you need to process a group of values in order.
DICTIONARIES
[+] - DICTIONARIES - [+]
Dictionaries store information in key-value pairs. They are useful when you want to label values rather than just store them by position.
person = {
"name": "Alice",
"age": 25,
"city": "Seattle"
}
You can access individual values using the key:
print(person["name"])
print(person["age"])
You can also update dictionaries or add new values:
person["age"] = 26
person["job"] = "Analyst"
print(person)
And you can loop through key-value pairs like this:
for key, value in person.items():
print(f"{key}: {value}")
Dictionaries are useful for things like usernames and passwords, configuration values, and structured records.
WHERE TO GO FROM HERE
We've covered some of Python's basic building blocks, but this is only the beginning of what you can create. Everything here should give you the foundation to start writing simple programs, but Python's real power emerges beyond the basics, especially in automation. Imagine automatically renaming files, sending emails, scraping data from websites, or organizing your photo library in seconds. Along the way, you've seen how to use if/else and for loops to work through large sets of data, convert between data types, manipulate strings and lists, accept user input, and use booleans and conditional logic to control the flow of your programs.
It may feel overwhelming now, but the goal of this post is just to get your feet wet. We've barely scratched the surface of what Python can do. Once you're ready to dive deeper, you can explore topics like object-oriented programming, powerful libraries such as pandas and requests, frameworks like Flask and Django, or even building GUI-based tools.
The best way to learn Python is to write Python. Start small, make mistakes, debug them, and keep going.