Introduction
Python is one of the most widely used, easy-to-learn, quick-to-understand and most convenient scripting languages; especially for cybersecurity, data science and machine learning. As the learning curve is simple enough to pick up and you can almost find a library for everything if you wish to automate if you search for it.
History
Python is an interpreted high-level programming language, meaning it reads and executes the codes line by line instead of compiling all at once like Golang or C#, etc. Python first appeared 30 years, in 1991. It’s author, Guido van Rossum began working on developing Python in the late 1980s, intended to be a successor to ABC programming language. As of today, Python consistently ranks as one of the most popular programming language.
Basics
We will just cover a few basics syntax and operator in Python, just to get a quick understanding of its elegance, readability and simplicity. If you want some hands-on practice, you can try the Python Basics room on TryHackMe.
We will cover basics in:
- Variables
- Loops
- Functions
- Data Structures
- If/elif/else statements
- Functions
- Imports
Print Statement
As with learning any programming language, we will start with a simple line print “Hello World”
print("Hello world!")
As simple as that!
Mathematical Operators
Operator | Syntax | Example | Output |
---|---|---|---|
Addition | + | 1 + 1 | 2 |
Subtraction | - | 6 - 3 | 3 |
Multiplication | * | 4 * 2 | 8 |
Division | / | 4 / 2 | 2 |
Modulus | % | 10 % 1 | 0 |
Exponent | ** | 5**2 | 25 |
Comparison Operators
Symbol | Syntax |
---|---|
Greater than | > |
Less than | < |
Equal to | == |
Not equal to | != |
Greater than or equal to | >= |
Less than or equal to | <= |
Variables and Data Types
We can define a variable by simply naming it and assign it a value separated by an equal sign, example:
variable_math_op = 3 + 4
variable_string = "Potato is the best vegetable!"
Python is an interpreted programming language, that means each line of code is read line by line; so if you define something in a certain line and redefine is later, it will use the latest line, example:
score = 500
score = score + 1
print(score)
# OUTPUT:
501
Data types are the classification of data items, it represents a king of value which determines what can be done with that data. The table below are data types of Python:
Data Types | Examples | Explanation |
---|---|---|
Strings | “Hello!” | Text; anything in between quotes |
Integers | 1234 | Whole numbers |
Floats | 21.6 | Decimal numbers |
Booleans | True/False | Truth value (yes/no) |
Lists | [1,2,3,“Hello”] | Collection of data between square-brackets separated by commas |
Tuples | (1,2,3,4) | Collection of data between parenthesis separated by commas |
Dictionaries | {‘a’:1, ‘b’:2} | Collection of data with key/value pairs between curly braces separated by commas |
Logical and Boolean Operators
Logical operators allow assignment and comparisons to be made and are used in conditional 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 |
---|---|---|
Both conditions must be true for the statement to be true | AND | if x >= 5 AND x <= 100 |
Only one condition of the statement needs to be true | OR | if x == 1 OR x == 10 |
If a condition is the opposite of an argument | NOT | if NOT y |
If/elif/else Statements
Example codes:
name = "jinx" hungry = True
if name == "jinx" and hungry == True:
print("jinxis hungry")
else if name == "jinx" and not hungry:
print("jinx is not hungry")
else: # If all other if conditions are not met
print("Not sure who this is or if they are hungry")
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). Let’s break this down:
- The i variable is set to 1
- The while statement specifies where the start of the loop should begin
- Every time it loops, it will start at the top (outputting the value of i)
- Then it goes to the next line in the loop, which increases the value of i by 1
- Then (as there is no more code for the program to execute), it goes to the top of the loop, starting the process over again
- The program will keep on looping until the value of the i variable is greater than 10
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. Let’s break this down:
- The list variable called websites is storing 3 elements
- The loop iterates through each element, printing out the element
- The program stops looping when it’s been through each element in the loop
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
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))
Importing a library
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.
import datetime
current_time = datetime.datetime.now()
print(current_time)
Conclusion
And that’s the end, stay tuned! We’ll also soon go through basics in Ruby, PowerShell, Perl, and Bash.