Introduction to Python
Last updated
Last updated
Shameless plug
This course is given to you for free by the Malcore team: https://m4lc.io/course/python/register
Consider registering, and using Malcore, so we can continue to provide free content for the entire community. You can also join our Discord server here: https://m4lc.io/course/python/discord
We offer free threat intel in our Discord via our custom designed Discord bot. Join the Discord to discuss this course in further detail or to ask questions.
You can also support us by buying us a coffee
NOTE: This course assumes that you have Python installed and can successfully run Python programs.
Most of the time you'll probably hear people talking shit about Python or telling you that you should learn another language entirely. Which is fair, there are plenty of programming languages in the world and a lot of them function the exact same way: you write the code, you compile/interpret the code, the code runs and does what you want it to do. So why should you choose Python? Well first of all this course is not an argumentative essay. I personally don't care what you use, but if you're going to use Python here's some key factors of why it's a decent language:
Easy to learn
Python's syntax is pretty straight forward and is designed to be readable and intuitive. Once you grasp it, you can pretty much read any code thrown at you.
Versatile
Python is actually extremely widely used, its compatible with multiple operating systems and architectures, and can basically do anything that any other language can do, including running assembly code directly inline.
Multiple paradigms
Basically this just means that Python can be object-oriented programming (OOP) or functional oriented (using functions over classes)
This course will be designed to teach you the basics of Python and provide you with the basic understanding of it. The hope is that after this course you'll be able to pickup an editor and start coding successfully.
NOTE: This course assumes that you have Python preinstalled and have a basic understanding of programming.
To start we should talk about variables. A variable is basically just a piece of code that stores something for later usage. Variable names must be a-zA-Z
and can contain an underscore (_
). An example of a Python variable:
The above provides a decent example of a variable. We created a variable named name
that equals =
the string Malcore
. Now later on down the road we can call that variable by using the variable name name
. You can also create variables using integers:
This variable age
contains the integer: 5
. But what if you want to be able to tell if a variable is True
or False
? Well, those are called booleans and look something like this:
As you can see we set the variable is_young
to True
and the variable is_old
to False
. As an added bonus Python inherits it's boolean structure from earlier languages like C, what this means is that booleans are also equal to integers:
So if you're feeling really fancy or just want to piss people off, you can use booleans in place of integers or integers in place of booleans.
In Python you can reassign variables to another name. For example:
What we just did was set variable one
to the integer 1
and set variable two
to the integer 0
so that one
equals 1
and two
equals 0
. Now we set variable one
to the value of variable two
(or 0
) and set variable two
to the new value of variable one
(which is 0
) we then print
both variables to display the values. Being able to rename variables dynamically is useful for things like avoiding conflicting names.
As you have already seen above using variables is pretty straight forward, so we will give you an indepth example of variable usage:
The above provides a good overview of what we have already talked about, including renaming variables. So at the end the variable x
is equal to the value of the variable b
which is the integer 40
.
A cool thing about variables is that you can perform multiple variable assignments on one line of code in multiple different ways:
This provides a quick way to set variables in line with one another.
Of course, with everything there comes rules or "best practices". Before we get into the best practices, I want you to really understand programming is about doing what you want to do. Yes, readable and maintained code is important, but you should never be a slave to the rules. If you find something that works better for you, you should do that instead.
Variable names should always describe their purpose. If you're adding multiple prices together and the end value is x
you should set the end value to total_price
to clearly show what you are trying to accomplish.
Always use consistent naming conventions. In Python variable name conventions are snake_case
all lowercase using underscores (_
) as spaces.
The print
statement is one of the most used functions in Python. It is a built-in function that allows you to print data to the console, or display output to the user. The print function also can handle unicode characters. It is extremely easy to understand so this section will be short:
Python has built-in syntax to help with doing math and arithmetic operations. The are as follows:
Addition
Addition in Python is pretty straight forward
It is also possible to perform addition by adding to an already declared variable:
Subtraction
Subtraction, much like addition, is pretty straight forward. You can also perform the same concept as in addition by using a preset variable to subtract from. In this example we will do both:
Arithmetic syntax table
There are plenty more arithmetic operators but for this course we will not be going into them. Below is a table of all the operators and information about them if you want to understand more:
Python itself has multiple data types. Data types are categories of values (or data) that you can work with in a program. The understanding of data types is crucial for any developer, new or seasoned, to determine what kind of operations can be done on that data. For example, an integer cannot be treated like a string.
Numeric
Types: ints, floats, complex
Ints:
Whole numbers without decimal points: 3
Floats:
Numbers with decimal points: 3.12
Complex:
Numbers that have both real and imaginary parts: 3j
NOTE: Imaginary numbers are denoted by j
in Python.
Strings
Types: single line, multi line
Single line:
A single line string that is between "
or '
: "this is a string" + 'this is also a string'
Multi line:
A string that takes up multiple lines between either """
or '''
:
NOTE: strings are immutable objects. This means that once a string is created, you cannot directly change their characters. However, it is possible to edit strings in line using something like the following:
Booleans
Types: True, False
True:
This expression is often used for conditional statements
False:
Same as True
List
Lists are ordered collections of data and are mutable. This means they can be directly accessed and changed. You create lists using square brackets: []
. You might also know these as arrays
.
Tuple
Tuples are immutable lists, meaning that you cannot directly change them after the element is created
NOTE: tuples are used for when the data needs to remain constant and should never be changed
Dicts (dictionary)
A dict is an unordered collection of key and value pairs. Each key must be unique and are used to access the values associated with them. You call a dict by using: {}
Set
A set is an unordered collection of unique items. There are no duplicates allowed in a set. You create a set by using: {}
or set()
NoneType
None
is a special type that represents the absence of data. Much like null
. This signifies that something is empty
It is possible to determine what type an object is by using the following:
You can also determine if an object is an instance of a type by doing the following:
These help determine the types and allow you to make decisions based off that type.
Control structures allow you to control the flow of the program based on conditions, repetitions, and other logical indicators. These will help make decisions on what to do with the code.
Conditional statements
These allow you to make decisions based on certain conditions:
The above example provides a decent explanation of how conditional statements work. There is not a limit to how many elif
conditions there can be.
Loops
Loops allow you to execute a block of code multiple times. There are for
loops and while
loops.
for
loop
This loop iterates of a sequence of data
This loop will always stop after the sequence of data is finished. It will run its code block for each sequence of data presented. You can use lists
, tuples
, or strings
with a for
loop.
while
loop
This loop continuously runs until the condition set forth is False
This loop above will subtract 1 from count
every iteration until count
does not equal 0. It is worth mentioning that while
loops can be dangerous. The incorrect condition can create a forever loop that will continuously run and eat resources forever. An example of a forever loop is:
This loop will NEVER end.
Now that we understand the basics of loops we should start talking about how to break out of them earlier, skipping iterations, and loop controls. We will use for
loops for the remainder of these examples. You should always use for
loops unless you absolutely have to use a while
loop (I'm sure I'll get a lot of hate for that, I don't care).
Breaking out of loops
To break out of loops you use the break
statement. This statement allows you to stop the iterations of a loop immediately.
The above code shows you exactly how the break
statement works. It runs through the code until a condition with an if/else
statement is met, it will then print to the screen and break the iterations.
Skipping iterations
To skip iterations all you have to do is use the continue
or the pass
statement. The difference between these two statements is that a pass
statement indicates there is nothing to execute and acts as a type of nop
. A continue
statement forcibly skips the iteration of the loop. pass
is usually used to indicate future code.
Using the pass
statement:
Using the continue
statement:
Loop control
Sometimes in a loop you need to execute something right after the loop finishes normally. When there is no break statement encountered. You can accomplish this by using an else
in the loop. For example:
Now if we do the same thing and make the list longer:
A function is a reusable block of code that performs a specific task. They help to organize your code and make it more modular while allowing you to reuse the function itself to perform the same block of code. Functions should solve one problem, and solve it well. The key concepts of a function are: the definition of it (declaring the function), the execution of the function itself (what does it do), the parameters that can be taken by the function (arguments that you can pass to it), the return value (what does the function return if anything). To define a function in Python you use the def
statement. Here is an example:
It is worth mentioning that functions can take multiple positional arguments as well as multiple keyword arguments. There are a couple ways to do this:
As you can see the **kwargs
arg is a dict
where you can access the keyword argument by using the key
, and the positional arguments are tuple of data.
Now that you have a basic grasp on how all this works we will write a basic program that incorporates all the information we have gone through. We will be writing a basic calculator:
Let's break down this code to fully understand what is happening:
This function takes two arguments and adds those two arguments together. For example add(2, 2)
will equal 4
.
This function also takes two arguments and subtracts them from one another. For example subtract(3, 1)
will equal 2
.
This function creates a basic help menu for the user to see by adding newlines it makes it on a single line.
This function is the main logic of the program and has the control flow for the entire program. It has an infinite while
loop that will never end that wraps all the other logic. The first thing it does is display the help menu and take the users input to take the appropriate action.
That's all there is to it! You have learned the basics of Python and successfully built your own calculator program. We hope this course has given you the basic understandings of programming in Python and you have learned something.
Please remember that this course is provided for free by the Malcore team. Please consider following one of the below links:
Register for Malcore: https://m4lc.io/course/python/register Join our Discord to discuss: https://m4lc.io/course/python/discord
operator | use case | example |
---|---|---|
+
Adds two numbers
10 + 10
-
Subtracts two numbers
3 - 1
*
Multplies two numbers
2 * 2
/
Divdes the first number by the second number, will return a float
9 / 3
//
Divides the first number by the second number and rounds down to the nearest whole number
3 // 2
%
Returns the remainder of the division between the first and second number
100 % 10
**
Raises the first number to the power of the second number
3 ** 3