Python from absolute zero. Learning to code without boring books

Date: 30/05/2025

If you think a hacker doesn’t need programming, you’re deeply mistaken! Yes, you can rock Kali Linux and use premade programs, copy code from forums, and blindly download scripts from GitHub. But your skill limit until you learn to write and understand code will be low. In this article, I will try to teach you the basics of programming in an accessible form. Starting from zero!

From the editors

We recently conducted a survey on which Python course would be more interesting to readers. The first two strings in it occupied the options “for the hacker” and “Python from scratch”. Upon learning about this state of affairs, we immediately ordered an article on how to start programming in Python. If it succeeds, it could turn into a whole series. What makes our approach different is that we explain everything in living language and give non-boring examples. Basically, training in the brand style of a Hacker!

And since this is an experiment, the article is available without a paid subscription.

If you have a modern Linux distribution on your computer, it already includes Python 3, and writing the first programs will be convenient in IDLE, a simple code editor that comes with Python. In Ubuntu, to install it, type in the console

sudo apt-get install idle3

On Windows, when installing Python, tick Add to Path on the first screen of the installer to allow running python3 from the command line in any convenient place.

After running IDLE, go to Options → Configure IDLE, go to the General tab, and tick Open Edit Window, click OK, and restart IDLE. You can now write programs, save them, and run them with the F5 key. Here we go!

Variables

Any programming language has a thing called variables. It’s like school algebra: here’s the variable a = 1, here’s the variable b = 2. I mean, these are such abstract things, inside of them lies a value that can change – for example, when you write after a variable, a sign equals and some new value.

a = 2
a = a + 2
print(a)

Well, you have already realized that print(a) is a command that prints the current value of a variable on the screen. You wrote the variable + 2 again after the equals sign, so first, there was a value of 2 in the variable, then 2 more were added to this value. The screen proudly displays 4. Congratulations, you put two and two together!

And if it is not initially known, what numbers should be added? Then you would first have to ask the user to type them into the console and press Enter. Let’s do this:

a = input('Enter how many liters of beer you have: ')
b = input('How many beers did a friend bring:' )
c = int(a) + int(b)
print('For both of you: ' + str(c) + ' liters of beer')

Inside the parentheses at the input, write an explanation for the user, what exactly he is asked to enter. But the problem is, by default, everything entered via input is considered not a number, but a string, so before adding the number of liters of beer, you must first convert the entered strings into numbers using the int() function.

info

The word “function” should be familiar to you from mathematics. In parentheses we write what it accepts (the argument), and there will be a result on the output. Python will first replace the variable with its current value (int(a) with, say, int("5"), and then the function with the execution result, that is, 5. Sometimes, the function returns nothing, only does something. For example, print() only prints an argument.

Okay, so I converted the strings into numbers, put them in the c variable, and then what’s the dash inside the parentheses at print? Here are strings (the strings are always written inside quotation marks) explaining what exactly is displayed, and the result of addition is passed to print() function.

For the strings to painlessly add to a c variable containing a number, you need to convert it into a string with the str() function, just as we converted strings into numbers, only the opposite.

In general, there are many types of variables, but you get the point — to do something with variables, you need to first lead them to one type — to a string, or to a numeric, or something else. Not to worry about it, Python doesn’t add up the numbers, but the strings, and the entered 2 and 3 liters of beer add up to not 5 but as many as 23. It would be nice to be real!

Here’s another example that calculates how long you can drink beer based on the average life expectancy in Russia:

a = input('Enter how old you are: ')
b = 73 - int(a)
print('Approximately: ' + str(b) + ' years')

Here, we call the function input() to get a value, subtract it from 73 (the average life expectancy of a Russian), remembering to turn a string into a number, and then print the result by turning the number back into a string and adding other strings.

So you learned what are integer and string variables, that you can convert these types into each other with int() and str(). In addition, now you can get variables from the user using the input('Enter something') function and print results using the print() function.

Conditions

Any program is based on conditions. Depending on whether they are implemented or not, the program may follow one or another path. Imagine driving and looking at the clock: if it’s already 10 p.m., you turn home, if not, you can stop by for a visit. The program also works the same way: checks a value and collapses there or here and executes the corresponding piece of code.

beer = input('Enter Yes if there is beer, and No if there is no beer: ')
if beer.lower() == 'yes':
result = 'You will hack the Pentagon.'
else:
result = 'You will break your brain.'
print(result)

If means “if” in English, and else means “other” or “otherwise”. In the string after if, there is a condition that we check. If this is correct, the first block of code is executed (it is separated by four spaces at the beginning). If not, the one after else:.

info

Blocks of Python code are indented. Indentation can actually be anything, for example some prefer to use the Tab key instead of four spaces. The key is not to mix indentations of different types in one program. If you already started using four spaces, then use them throughout the program, otherwise Python will curse and humiliate you.

Another important point here is the sign of equality in conditions. It is written as a double ‘equals’ (==) and thus differs from assignment, a single ‘equals’.

The lower() function makes all letters in a string small before comparing the condition, because a stupid user can enter the word YES with active Caps Lock, and this must be provided in advance.

info

Actually, lower() is not just a function, but a method of string class. This is why it is called after the point after the variable that contains the string. We will talk about classes and methods some other time, but just remember that some functions are called this way.

Let’s try making a condition for checking the login and password using the AND statement, which is written as and. It is needed to verify that the first and second conditions are met simultaneously.

myname = input('Enter login: ')
mypass = input('Enter password: ')
if myname == 'xakep' and mypass == 'superpassword123':
result = 'Welcome, O great hacker!'
else:
result = 'Who are you, goodbye...'
print(result)

info

The Python operator is a character that performs an operation on one or more variables or values: arithmetic (“plus”, “minus”, “equals”, etc.), comparisons (double “equals”, “greater”, “less”, “less”, etc.), assignments (as well as several others), logical operators (and, or, not), membership operators (in, not in), and is, is not). There are also bitwise operators for comparing binary numbers.

Let’s create an even more complicated condition using the or operator, which translates to OR.

myname = input('Enter login: ')
mypass = input('Enter password: ')
if(myname == 'ivan' and mypass == 'superpassword123') or (myname == 'marina' and mypass == 'marinka93'):
result = 'Hello, ' + myname + '. Welcome!'
else:
result = 'Who are you, goodbye...'
print(result)

Parentheses are used here — Python doesn’t require parentheses for simple conditions, but for complex ones they are used to explicitly define the order of operations. The program welcomes only two users, ivan or marina. So first, it checks if Ivan’s login and password didn’t match, and then after the or operator it checks for Marina.

info

When you want to check not one condition, but two or three at once, you can bracket each condition, and put or or and between them. In case of or, the general condition is fulfilled, if at least one of its conditions is fulfilled. In the case of and for a general condition to be met, both conditions must be met.

Here’s another example, it uses elif, which means something like ELSE-IF. This is used to specify several blocks of commands: if one condition is not met, the following is checked using ELIF, and so on.

v = int(input('Enter how old you are: '))
if v < 18:
print('Hello, young cracker')
elif v < 30:
print('Hi, old school')
elif v < 65:
print('Switching from assembler to Python?')
elif v < 100:
print('Retirement is the right time to code')
elif v < 100000:
print('The Clan of Immortals greets you!')

Different comparison operators can act as conditions:

  • a == 9 (a is equal to 9)
  • a != 7 (a is not equal to 7)
  • a > 5 (a is more than 5)
  • a < 5 (a is less than 5)
  • a >= 3 (a is more than or equal to 3)
  • a <= 8 (a is less than or equal to 8)

You can also invert the condition true to false and back with the word not.

beer = input('Enter Yes if there is beer, and No if there is no beer: ')
if beer.lower() == 'yes':
print('No beer!')
if not beer.lower() == 'yes':
print('Hooray, there is still beer!')

For example, you need a person to enter a number at least (NOT) 5.

x = int(input('Enter how many liters of beer you have: '))
if not (x < 5):
print('It is okay, we can start hacking')
else:
print('Beer is not enough.')

Lists

Regular variables are good for storing single values, whether a string or a number. But sometimes you need to store a group of variables. This is where lists come to help you.

For example, a list could be:

a = [67,5,90,20,30]

Each item in the list has its own index. To get one of the list values, you can refer to its serial number. Numbering in the lists goes not from one, but from zero, that is, 0, 1, 2, 3, 4…

print(a[2]) command will print the number 90, the third element (the number from scratch!) in the list above. There can be as many items as you want.

You can also make a list of strings:

b = ['Masha', 'Vanya', 'Lena', 'Marina', 'Arnold']

Then print(b[1]) will print Vanya string.

You can add a new value to an existing list using the append method:

b.append('Dima')

Now, the list looks like this:

b = ['Masha', 'Vanya', 'Lena', 'Marina', 'Arnold', 'Dima']

If you need to refer to some list element, counting from the end of this list, you can write negative numbers. For example, the last item in the list is -1, and print(b[-1]) will print Dim.

Any list can be sorted ascending or alphabetically.

a = [67,5,90,20,30]
a.sort()

After performing a.sort() function, the list will take the form [5,20,30,67,90].

Now, a little bit about the slices. A slice is as if receiving some part of a list, which in turn is also a list. Slices are specified as follows:

list[x:y:z]

Here, x is the number of the element from which the slice is taken, y is the last element of the slice, z is the interval at which we take the elements (an optional value).

We get a slice of list b elements from 1 to 3 (4 not included in the slice):

print(b[1:4])

Get a slice of list b elements from 2 to the end:

print(b[2:])

Get every other item in the list:

print(b[::2])

We reverse the order of the list items:

print(b[::-1])

By the way, ordinary strings also support slices, their result will also be a string. For example:

s = 'Hello world'
print(s[:5])

‘Hello’ will appear on the screen, because we printed the first five characters of the string.

Other lists can be elements of a list. To refer to the items in the list within the list, use another set of square brackets:

a = [[1, 2, 3], [44, 45, 46]]

Such a list of lists is called two-dimensional and resembles a table. For example, to get the first number in the second string (indexes 0 and 1, because the number is zero), you write:

print(a[1][0])

The result will be 44.

A list is a variable sequence. This means that if you create actions on the list, you do not have to override it and re-save it into a variable. But a string is an immutable sequence. If you do anything to it, you’ll have to put the new value somewhere.

Another invariable data type is the tuple. It’s the same list, but you can’t change it. So it takes less memory. You can declare a motorcade using parentheses:

a = (1, 2, 3, 4)

A set is another sequence of elements, each of which does not have its own index. However, all elements of a set are unique and not repetitive. If you want a set of unique elements, you can put them in a set. Let’s convert an existing list into a set and see that there are no repeating elements left in it. l = [1, 2, 2, 3, 3, 4, 1]

l = [1, 2, 2, 3, 3, 4, 1]
m = set(l)
print(m)

Result: set([1, 2, 3, 4]), i. e. repeated elements disappeared. By the way, if you want to turn a set (or something else) into a list, use the list() function. # Loops

Loops

A loop is a block of commands that is repeated a certain number of times. Loops can be specified in different ways. For example, the loop for is often used to go through all elements of a sequence like a list.

lst = [15,50,60,97,78]
for x in lst:
x = x + 1
print(x)

Here you start with a list of numbers, and then you use the for x in lst construct to go through each element of this list one by one and do something with it. These actions, as with conditions, are indented.

The x variable , in this case, takes the value of each element of the lst list one by one, adds one to this value, prints the result, and then proceeds to the next round of the loop, i. e. takes the next value in the list and does the same with it, and so until the list ends.

If you just need to execute commands a specific, predetermined number of times, then use the for loop and range() function.

num = 0
for i in range(5):
num=num + 1
print('I' + str(num) + 'beer')

If you have any list, you can easily run through it in a loop:

mas = ['Lenin', 'Stalin', 'Khrushchev', 'Brezhnev', 'Gorbachev', 'Yeltsin', 'Putin', 'Medvedev']
# Oh yes, Putin came back. We need to add it again.
mas.append('again Putin')
for x in mas:
print('Was '+ x + ' and then... ')

Now it’s time to learn about the while list. The word while translates from English as “until” (not in the sense of “goodbye”, but in the sense of “until”). That is, the commands inside the loop will be executed as long as the condition specified below is met. For example, here is a loop that will print all even numbers from 1 to 100.

a = 0
while a < 100:
a = a + 1
if (a % 2) == 0:
print(a)

info

How did we check if the number was even? We’ve been helped by % operator, which returns the remainder of the division. If dividing in half makes zero, then the number is even!

The while loop must explicitly specify the change in the variable that is responsible for the condition, otherwise the loop may become infinite and the program will hang.

Going forward, I’ll show you how to create a very small but malicious script called a fork bomb. It endlessly creates its copies in RAM, which can cause quite a few brakes:

import os
while True:
a=os.fork()

Here, we do a new thing that is also worth remembering: we import a module, namely an os module that contains commands for accessing various functions of the operating system.

Then inside the while loop, we create endless copies. As a condition, we have written here simply True, that is, simply ‘true’. The loop body does not change this value, so the loop will execute over and over again, and os.fork() will produce new and new processes, clogging up RAM with them. So, mate, be careful with the while loop!

Practical task: monitor the clipboard

Now let’s move on from case studies to something interesting! After all, we’re not just studying programming out of curiosity. Let’s write a program that monitors what’s happening on the clipboard.

One of Python’s strengths is its huge database of off-the-shelf modules that you can pick up and plug into your programs. To install and use them within your programs, you can use a package manager called pip. Let’s assume you already have a pip installed.

First of all, we put a pip module that is responsible for working with the clipboard. In Windows, it will be a command like this:

pip install pyperclip

In Linux — slightly different:

pip3 install pyperclip

Proceed to coding. Our software will monitor the clipboard and print any text the user copies on the screen. I explained them in the form of comments, they are beaten in Python by a # sign at the beginning of the string.

# Connect the clipboard module
import pyperclip
# Connect the module to work with system time
import time
# We set the variable old and assign an empty string to it
old = ''
# Start an endless clipboard tracking loop
while True:
# We put the clipboard contents in variable s
s = pyperclip.paste()
# If the received content is not equal to the previous one, then:
if(s != old):
# print it
print(s)
# write the currently caught value to the old variable
# so that the next round of the loop does not repeat and print what is already caught
old = s
# At the end of the loop, we pause for one second to allow the clipboard contents to load
time.sleep(1)

Well, congratulations, you wrote a program that can catch anything a user copies to the clipboard. It can be further developed — for example, instead of displaying it, write the caught strings to a file with a log or send them over the network. But we just started, right?

Homework

Let me give you some homework you can do, so you can practice on your own.

  1. Make a program that calculates your ideal weight based on height and age. Find the corresponding formula in search engines and fulfill the condition for calculation. Beer’s a beer, and you gotta watch your health!

  2. Write a program that in a loop monitors the clipboard, periodically getting text from it using pyperclip.paste(), and if it sees that someone has copied email, replaces this email with another one pre-defined in the code, placing it on the clipboard with the command pyperclip.copy('coolhacker@xakep.ru').

[ Post back in the comments if you found this article helpful!

If the topic turns out to be in demand, then in the next article, we will look in detail at working with strings, files, look at the Internet, and again dabble in writing the simplest possible hacker scripts.

Related posts:
2023.06.08 — Cold boot attack. Dumping RAM with a USB flash drive

Even if you take efforts to protect the safety of your data, don't attach sheets with passwords to the monitor, encrypt your hard drive, and always lock your…

Full article →
2022.06.01 — First contact. Attacks on chip-based cards

Virtually all modern bank cards are equipped with a special chip that stores data required to make payments. This article discusses fraud techniques used…

Full article →
2022.06.02 — Climb the heap! Exploiting heap allocation problems

Some vulnerabilities originate from errors in the management of memory allocated on a heap. Exploitation of such weak spots is more complicated compared to 'regular' stack overflow; so,…

Full article →
2022.01.13 — Step by Step. Automating multistep attacks in Burp Suite

When you attack a web app, you sometimes have to perform a certain sequence of actions multiple times (e.g. brute-force a password or the second authentication factor, repeatedly…

Full article →
2023.07.07 — Evil Ethernet. BadUSB-ETH attack in detail

If you have a chance to plug a specially crafted device to a USB port of the target computer, you can completely intercept its traffic, collect cookies…

Full article →
2023.04.20 — Sad Guard. Identifying and exploiting vulnerability in AdGuard driver for Windows

Last year, I discovered a binary bug in the AdGuard driver. Its ID in the National Vulnerability Database is CVE-2022-45770. I was disassembling the ad blocker and found…

Full article →
2022.06.01 — F#ck AMSI! How to bypass Antimalware Scan Interface and infect Windows

Is the phrase "This script contains malicious content and has been blocked by your antivirus software" familiar to you? It's generated by Antimalware Scan Interface…

Full article →
2022.02.09 — Kernel exploitation for newbies: from compilation to privilege escalation

Theory is nothing without practice. Today, I will explain the nature of Linux kernel vulnerabilities and will shown how to exploit them. Get ready for an exciting journey:…

Full article →
2023.02.12 — Gateway Bleeding. Pentesting FHRP systems and hijacking network traffic

There are many ways to increase fault tolerance and reliability of corporate networks. Among other things, First Hop Redundancy Protocols (FHRP) are used for this…

Full article →
2023.02.13 — First Contact: Attacks on Google Pay, Samsung Pay, and Apple Pay

Electronic wallets, such as Google Pay, Samsung Pay, and Apple Pay, are considered the most advanced and secure payment tools. However, these systems are also…

Full article →