LEARN >> Python Basics

Table of Content

This room will teach the basics of Python. Although it’s not necessary to know programming to succeed in security, it is a definitely a bonus to have. Python is one of the best to learn as it is so common, and also easy to pick up.

This room will cover:

  • Variables
  • Loops
  • Functions
  • Data Structures
  • If Statements
  • Files

Task 2 – Hello World

The first task is the ever popular "Hello World"… source below!

# This is an example comment
print("Hello World")

If a line starts with # then it is ignored by Python, these are used for comments.
We can use print() to ouput to the users screen, and anything between the () will be printed. Because we are printing a string, we must surround it in "".

Question(s) Exercise

See above…

Task 3 – Mathematical Operators

Lets cover mathematical operators and how they can be applied to Python. Like we have on our calculators, there are operations such as adding, subtracting, multiplying, and dividing; using Python we can code our calculator… after all, programming is just writing rules for the computer to follow given specific inputs and conditions.

  • The table below shows the different operations:
Operator Syntax Example
Addition + 1 + 1 = 2
Subtraction 5 – 1 = 4
Multiplication * 10 * 10 = 100
Division / 10 / 2 = 5
Modulus % 10 % 2 = 0
Exponent ** 5**2  = 25 (52)

Now that we know basic mathematical operators, lets move on to comparison operators; these play a big part in Python and will be built upon when we look at loops and if statements. These operators are used to evaluate a program’s condition at a particular state.

Symbol Syntax
Greater than >
Less than \<
Equal to ==
Not Equal to !=
Greater than or equal to >=
Less than or equal \<=

Task 4 – Variables and Data Types

Variables allow you to store and update data in a computer program. You have a variable name and store data to that name.

food = "ice cream"
money = 2000

In the above example, we have 2 variables. The variable named "food" stores the string (words) ice cream, while the other variable "money" stores the number 2000.

Variables are powerful as you can change them throughout your program. The below example shows the variable "age" initially being set to 30, then the second line takes the current value of age (age = age) and adds + another 1 to what "age" was already set to. Finally the last line prints the current amount in "age" to the screen.

age = 30
age = age + 1

There are 5 important to know data types that a variable can be set to, depending on what you store in them. You can store text, numbers, and many other types. The most important are:

Question(s) Exercise

In the code editor, create a variable called height and set its initial value to 200.
On a new line, add 50 to the height variable.
On another new line, print out the value of height.

height = 200
height = height + 50

Task 5 – Logical and Boolean Operators

Logical operators allow assignment and comparisons to be made and are used in conditional testing (such as if statements).

Logical Operation Operator Example
Equivalence == if x == 5
Less than \< if x \< 5
Less than or equal to \<= if x \<= 5
Greater than > if x > 5
Greater than or equal to >= if x >= 5

Boolean operators are used to connect and compare relationships between statements. Like an if statement, conditions can be true or false.

Boolean Operation Operator Example Explination
Both conditions must be true for the statement to be true AND if x >= 5 AND x \<= 100 Returns TRUE if x is a number between 5 and 100
Only one condition of the statement needs to be true  OR if x == 1 OR x == 10 Returns TRUE if X is 1 or 10
If a condition is the opposite of an argument NOT if NOT y Returns TRUE if the y value is False

Here is a few examples of the above:

a = 1
if a == 1 or a > 10:
     print("a is either 1 or above 10")
name = "bob" hungry = True
if name == "bob" and hungry == True:
     print("bob is hungry")
else if name == "bob" and not hungry:
     print("Bob is not hungry")
else: # If all other if conditions are not met
     print("Not sure who this is or if they are hungry") 

Task 6 – Shipping Project – Introduction to If Statements

If statements are essential in programming, and will be something you use a lot.

If statements allow progams to make decisions depending on what condition you set. The below code is an example of how an if statement can be used to determine the outcome of a program.

if age < 17:
    print('You are NOT old enough to drive')
    print('You are old enough to drive')

In the above example, if you are below the age of 17 then the program will tell you that "you are NOT old enough to drive", whereas if you are over the the age of 17 it will tell that "you are old enough to drive".

To explain differently, in an if statement; it depends on what the condition (in this example – age) is as to what the program will output.

  • Lets break down the if statement code:
    • The if keyword indicates the beginning of an if statement, followed by a set of conditions.
    • The if statement is only run if the condition (or sets of conditions) equal to true. In our example it’s age < 17; if that condition is true (age is below 17), the code within the if statement (the indented code) will run.
    • Per the example, if certain conditions are not met, the program can default to running the code shown after the else part of the statement.
    • A colon : marks the end of the if (or else) statement.
    • Note the indentation. Anything after the colon that is indented is considered part of the if statement, which the program will execute in order until the indentation ends.

Here is a graphical representation of the if statement from above:

Question(s) Exercise

In this exercise, we will code a small application that calculates and outputs the shipping cost for a customer based on how much they’ve spent.

In the code editor, click on the "shipping.py" tab and follow the instructions to complete this task.


 In this project, you'll create a program that calculates the total  
 cost of a customers shopping basket, including shipping.  

 - If a customer spends over $100, they get free shipping  
 - If a customer spends < $100, the shipping cost is $1.20 per kg of the baskets weight  

 Print the customers total basket cost (including shipping) to complete this exercise.  


customer_basket_cost = 34  
customer_basket_weight = 44  
total_cost = 0  

# Write if statement here to calculate the total cost  
if customer_basket_cost < 100:  
    total_cost = customer_basket_cost + (customer_basket_weight * 1.20)  

Task 7 – Loops

In programming, loops allow programs to iterate and perform actions a number of times. There are two types of loops, for and while loops.

While Loops

Let’s start off by looking at the structure of a while loop. While loops can run indefinitely (as in, until the program is terminated) or – much like if statements, we can determine how many times the while loop is ran based on a condition.

i = 1
while i <= 10:
     i = i + 1

This while loop will run 10 times – at every iteration (each loop) it will report the value of i and then increase it by 1.

  • Lets break it down further:
    • The i variable is set to 1.
    • The while loop instructs Python that it is to keep going until i is no longer less than or equal to (<=) 10.
    • The first line of the while loop (indentation!) we print the value of i to the screen.
    • The second line of the while loop sets i to the current value of i and adds + an extra 1, increasing the number by 1.
    • Since there is no more indented commands, the program will jump back to the while loop, and like an if statement – will keep going through each step of that loop until the condition equals false – in the examples case as soon as i is equal to 11, the loop will stop because 11 is greater than 10 and the returned answer to the condition i <= 10 is false.

For Loops

A for loop is used to iterate over a sequence such as a list. Lists (or arrays) are used to store multiple items in a single variable, and are created using [] square brackets (see the code below).

  • Here is an example of a for loop:
websites = ["facebook.com", "google.com", "amazon.com"]
for site in websites:

Since there are 3 strings stored in the list, the above for loop will only run 3 times, each time printing out the strings in the order the list currently shows.

In python, we can also iterate through a range of numbers using the range() function. Below is some example Python code that will print the numbers from 0 to 4. In programming, the number 0 is often the first number in a range, and when using the range command, we are not asking it to count TO 5, we are asking it to count 5 numbers – that is why it will return 0 to 4.

for i in range(5):

Question(s) Exercise

This one was relatively simple – a slight variation to the example code for while loop above, here is the code:

i = 0  
while i <= 50:  
    i = i + 1

Or alternatively, use a slight modification to the for loop just above this section and you can do the same:

for i in range(51):

HINT: the number in the range bracket is 51. The task asks you to "code a loop that outputs every number from 0 to 50" – for loops using range will stop at 49 if we put 50, so we add the extra 1 to 50.

Task 8 – Bitcoin Project – Introduction to Functions

When you start to code larger projects, it is highly likely your code will start to become "repetative" – repeating a lot of calculations, printing similar text over and over again… Fortunately this is where functions come in.

Functions are basically like "mini-programs" – small blocks of code, that you can call whenever you want in your code to do it’s task, and most importantly, as many times as you wish.

You could code a function to do some form of calculation for you – rather than having to write out the code every time to do that calculation for you, all you do is write a function that takes the two numbers you give it, and write the code to calcuate in the function, therefore the code in the function does the calculation, and all you have to do is call that fuction with the 2 numbers every time you needed it in your code.

  • Here is an example of a function:
def sayHello(name):
     print("Hello " + name + "! Nice to meet you.")

sayHello("ben") # Output is: Hello Ben! Nice to meet you
  • Let’s break down the line that defines the fuction:
    • The def command indicates the beginning of a function and is short for "define".
    • The function is followed by a name (in the examples case, it’s sayHello).
    • Directly after the name of the function, by default you need at least a pair of parethesis () – however, between these parenthesis we can optionally declare any input values needed by the function (in our examples case, name). These input values are considered variables in the scope of the function – in other words, variables that hold the data we pass to the function, but can be used only within the functions code (they are no longer usable once we break out of the function).
    • Finally, directly after the name and parenthesis, we need a : to declare the end of the fuction definition

Functions, much like if statements and for / while loops, require the code to be indented to signify what is part of the function.

  • A function can also return a result, see the code block below:
def calcCost(item):
     if(item == "sweets"):
          return 3.99
     elif (item == "oranges"):
          return 1.99
          return 0.99

spent = 10
spent = spent + calcCost("sweets")
print("You have spent:" + str(spent))

If we call the calcCost function and pass in "sweets" as the input value for item, the fuction will return a decimal number (float). In the code we take a variable called spent and add the cost of "sweets" via the calcCost function. As we can see from the function‘s code above; when we call calcCost with "sweets" it will return 3.99 – therefore since spent was 10, 10 + 3.99 = 13.99.

NOTE: the one thing that this task did not mention and I believe should have is why spent at the end of the print() function is surrounded by str() – this is because the + before the variable is telling Python to add spent onto the end of the string, but because we are printing a string, we need to convert the float spent into a string. If the surrounding str() was missing, the code would not execute because you would be trying to merge a different variable type float onto the current variable type string.

Question(s) Exercise

Let’s just copy this part straight from the task…

You’ve invested in Bitcoin and want to write a program that tells you when the value of Bitcoin falls below a particular value in dollars.

In the code editor, click on the bitcoin.py tab. Write a function called bitcoinToUSD with two parameters: bitcoin_amount, the amount of Bitcoin you own, and bitcoin_value_usd, the value of bitcoin in USD. The function should return usd_value, which is your bitcoin value in USD (to calculate this, in the function, you times bitcoin_amount variable by bitcoin_value_usd variable and return the value). The start of the function should look like this:

def bitcoinToUSD(bitcoin_amount, bitcoin_value_usd):

Once you’ve written the bitcoinToUSD function, use it to calculate the value of your Bitcoin in USD, and then create an if statement to determine if the value falls below $30,000; if it does, output a message to alert you (via a print statement).

 In this project, you'll create a program that that tells  
 you when the value of your Bitcoin falls below $30,000.  

 You will need to:  
 - Create a function to convert Bitcoin to USD  
 - If your Bitcoin falls below $30,000, print a message.  

 You can assume that 1 Bitcoin is worth $40,000  


investment_in_bitcoin = 1.2  
bitcoin_to_usd = 40000  

# 1) write a function to calculate bitcoin to usd  

def bitcoinToUSD(bitcoin_amount, bitcoin_value_usd):  
    usd_value = bitcoin_amount * bitcoin_value_usd  
    return usd_value  

# 2) use function to calculate if the investment is below $30,000  

bitcoin_value = bitcoinToUSD(investment_in_bitcoin, bitcoin_to_usd)  
if bitcoin_value <= 30000:  
    print("value too low - " + str(bitcoin_value))

Task 9 – Files

In Python, you can read from and write to files. It’s common to write a script and import or export it from a file; whether you are trying to output results from your code to a file, or read in a text file with 100’s of websites (or passwords) from a file to enumerate. Let’s jump straight into an easy example:

f = open("file_name", "r")

To open the file, we use the built-in open() function, and the second parameter – "r" denotes that we want to open the file in read mode (since we are only reading the contents); and finally the file is being referenced in the f variable. The second line simply prints the contents of the file, using f.read(), which is simply read the contents of the file referenced by f. You could also use readlines() rather than read() and push that through a loop to read each line – useful if we have a file to read in that contains an item on each line (say a username list, password list, directory list, etc…)

In the above example, the "file_name" string given during open() can either point to a file stored in the same directory as the Python script, simply by setting the string to the name of the file – e.g. "flag.txt", or if the file is in a different folder on the machine, you would have to point to the full path – e.g. /root/flag.txt.

You can also create and write to files. If you are writing to an existing file, then we use "a" as the second string in the open() function – this is short for "append" as we will be appending to a file that already contains data. If we wanted to start a new file, we would use "w" instead (which stands for "write"). See the examples below:

f = open("demofile1.txt", "a") # Append to an existing file
f.write("The file will include more text..")

f = open("demofile2.txt", "w") # Creating and writing to a new file
f.write("demofile2 file created, with this content in!")

Notice that at the end of each of these files, we call f.close()? This will close the file so it is no longer open, and free to be read / written to by other applications or users. This also means that Python no longer can write to the file, and the value of f becomes null (null is another way of saying the variable is blank, it no longer contains anything – the null terminology is commonly used in programming).

Question(s) Exercise

This one is pretty straight forward after the theory above… in fact, the code is all there, with one simple change – we have our flag!

f = open("flag.txt", "r")  

Task 10 – Imports

In Python, we can import libraries, which are collections of functions that we can use in our own programs. The beauty of libraries is that a lot of the hard work has already been done for you – for example, there is a datetime library that gives you access to hundreds of different functions related to date and time.

import datetime
current_time = datetime.datetime.now()

we import other libraries using the import function. Then when we want to use one of the libraries we have imported, we reference the library we imported to call the function in the format library_name.library_function().

In the example above, we import datetime on the first line, then on the second line we set the current_time variable to datetime.datetime.now() (it is doubled up in this example, because the fuction we are calling from the datetime library is called datetime, just to make things more confusing!)

Here are some popular libraries you will find useful when scripting as a pentester:

  • Request – simple HTTP library.
  • Scapy – send, sniff, dissect and forge network packets
  • Pwntools – a CTF & exploit development library.

Many of these libraries are already built-in to Python, however, libraries written by other people that are not already installed on your machine can easily be installed using pip install <MODULE_NAME>. Pip is Python’s package manager.

Leave a Reply

Your email address will not be published.