TryHackMe | Python Basics
Using a web-based code editor, learn the basics of Python and put your knowledge into practice by eventually coding a short Bitcoin investment project.
TryHackMe - Python Basics
Although programming isn’t required to succeed in security, it’s a great skill to have. As the “Scripting for Pentesters” module demonstrates, being able to program allows you to create security tools and create quick scripts that will aid you in hacking (as well as defending and analysing).
This room will teach you:
**Variables **Loops **Functions **Data Structures **If statements **Files In programming, syntax is important as it describes the structure of a valid programming language. In simple terms, syntax tells the computer how to read code using rules that control the structure of symbols, punctuation, and words of a programming language.
Task 2 : On the code editor, print “Hello World”. What is the flag?
print(“Hello World”)
'ANSWER: THM{PRINT_STATEMENTS}'
Task 3 : Mathematical Operators
# In the code editor, print the result of 21 + 43. What is the flag?
print(21+43)
'ANSWER: THM{ADDITI0N}'
# Print the result of 142 - 52. What is the flag?
print(142-52)
'ANSWER: THM{SUBTRCT}'
# Print the result of 10 * 342. What is the flag?
print(10*342)
'ANSWER: THM{MULTIPLICATION_PYTHON}'
# Print the result of 5 squared. What is the flag?
print(5**2)
'ANSWER: THM{EXP0N3NT_POWER}'
Task 4: On another new line, print out the value of height. What is the flag that appears?
height = 200
height+=50
print(height)
'ANSWER: THM{VARIABL3S}'
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 operators include = [ > , ≥ , < , ≤ , == ]
Boolean operators include = [AND, OR, NOT]
Let’s look at a few Python code examples:
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")
elif 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")
'ANSWER: No answer needed'
Task 6: Introduction to If Statements
Using “if statements” allows programs to make decisions. They let a program chose a decision based on a condition. Below is an example of how an if statement can be used to determine the section of code (which print statement) to use.
if age < 17:
print('You are NOT old enough to drive')
else:
print('You are old enough to drive')

If statements are essential in programming and will be something you use a lot.
Question 1: Once you’ve written the application in the code editor’s shipping.py tab, a flag will appear, which is the answer to this question.
"""
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
# Write if statement here to calculate the total cost
shipping = 0
if customer_basket_cost>=100:
shipping=0
else:
shipping_cost = customer_basket_weight * 1.2
total = shipping+ customer_basket_cost
print(total)
'ANSWER: THM{IF_STATEMENT_SHOPPING}'
Question 2: In shipping.py, on line 12 (when using the Code Editor’s Hint), change the customer_basket_cost variable to 101 and re-run your code. You will get a flag (if the total cost is correct based on your code); the flag is the answer to this question.
"""
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 = 101
customer_basket_weight = 44
# Write if statement here to calculate the total cost
shipping = 0
if customer_basket_cost>=100:
shipping=0
else:
shipping_cost = customer_basket_weight * 1.2
total = shipping+ customer_basket_cost
print(total)
'ANSWER: THM{MY_FIRST_APP}'
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 begin by looking at how we structure a while loop. We can have the loop run indefinitely or (similar to an if statement) determine how many times the loop should run based on a condition.
i = 1
while i <= 10:
print(i)
i = i + 1
This while loop will run 10 times, outputting the value of the i variable each time it iterates (loops).
For Loops
A for loop is used to iterate over a sequence such as a list. Lists are used to store multiple items in a single variable, and are created using square brackets (see below). Let’s learn through the following example:
websites = ["facebook.com", "google.com", "amazon.com"]
for site in websites:
print(site)
This for loop shown in the code block above, will run 3 times, outputting each website in the list.
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, 0 is often the starting number, so counting to 5 is 0 to 4 (but has 5 numbers: 0, 1, 2, 3, and 4)
for i in range(5):
print(i)
Question: On the code editor, click back on the “script.py” tab and code a loop that outputs every number from 0 to 50.
for i in range(51):
print(i)
'ANSWER: THM{L00PS_WHILE_FOR}'
Task 8 Bitcoin Project: Introduction to functions
As programs start to get bigger and more complex, some of your code will be repetitive, writing the same code to do the same calculations, and this is where functions come in. A function is a block of code that can be called at different places in your program.
You could have a function to work out a calculation such as the distance between two points on a map or output formatted text based on certain conditions. Having functions removes repetitive code, as the function’s purpose can be used multiple times throughout a program.
def sayHello(name):
print("Hello " + name + "! Nice to meet you.")
sayHello("ben") # Output is: Hello Ben! Nice to meet you
In the function, notice the indentation. Similar to if statements, anything after the colons that is indented is considered 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
else:
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 item parameter, the function will return a decimal number (float). In the code above, we take a variable called spent and add the cost of "sweets" through the calcCost function; when we call calcCost, it will return the number 3.99.
Question 1: 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).
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_to_usd * investment_in_bitcoin
return usd_value
investment_in_usd = bitcoinToUSD(investment_in_bitcoin, bitcoin_to_usd)
if investment_in_usd <= 30000:
print(“Investment below $35,000! SELL!”)
else:
print(“Investment above $35,000”)
'ANSWER: THM{BITC0IN_INVESTOR}'
Task 9 : Files
Question : In the code editor, write Python code to read the flag.txt file. What is the flag in this file?
f = open("flag.txt", "r")
print(f.read())
'ANSWER: THM{F1LE_R3AD}'
Task 10: Imports
In Python, we can import libraries, which are a collection of files that contain functions. Think of importing a library as importing functions you can use that have been already written for you. For example, there is a “date” library that gives you access to hundreds of different functions for anything date and time-related.
import datetime
current_time = datetime.datetime.now()
print(current_time)
We import other libraries using the import keyword. Then in Python, we use that import's library name to reference its functions. In the example above, we import datetime, then access the .now() method by calling library_name.method_name(). Copy and paste the example above into the code editor.
Here are some popular libraries you may find useful in 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 into the programming language; however, libraries written by other programmers not already installed in your machine can be installed using an application called pip, which is Python’s package manager. Let’s say you want to install the “scapy” library (which allows you to craft your own packets in code and send them to other machines); you install it first by running the command pip install scapy, after which in your program you can now import the scapy library.
Reference