Python is a general-purpose interpreted programming language that has now made its mark in the world of Computer Science and most importantly, for cybersecurity.
Join the channel Telegram of the AnonyViet 👉 Link 👈 |
This is not a standalone article that just explains what python is and introduces some basic commands. This article will be the starting point for other cybersecurity python articles. Note that during this process I will be using Python3 on Ubuntu 18.04.
The first step when learning python
Python can be installed from the standard linux apt repositories by entering the command sudo apt-get install python3
to install python3 in your machine. To use python you just need to type python in your Terminal it will take you to python’s shell.
robin@python:~$ python3 Python 3.6.8 (default, Jan 14 2019, 11:02:34) [GCC 8.0.1 20180414 (experimental) [trunk revision 259383]] on linux Type "help", "copyright", "credits" or "license" for more information. >>>
For Windows, you download Python For Windows, when installing at the first screen remember to select Add Path…. After the installation is complete, open CMD and type the command python
see if it works.
The basic concepts
Starting with the basics, I’ll explain the different concepts that will be used to understand what you’re doing and will also help you debug the program.
Variable
A variable that points to data stored in a memory location. A memory can typically hold strings, real numbers, Boolean values, integers, or more complex data types such as sets, lists, and dictionaries.
Note: In Python, you don’t have to explicitly define the data type like C/C++. Python strings can be enclosed in single or double quotes, no different than PHP/Perl.
Python 3.6.8 (default, Jan 14 2019, 11:02:34) [GCC 8.0.1 20180414 (experimental) [trunk revision 259383]] on linux Type "help", "copyright", "credits" or "license" for more information. >>> a_string = "Hello" # A string in duble quotations >>> a_string 'Hello' >>> a_string = 'Hello' # A string in single quotations >>> a_string 'Hello' >>> num = 5 # A integer value >>> num 5 >>> float = 1.34 # A float value >>> float 1.34 >>> Boolean = True # A boolean value >>> Boolean True >>>
Above, I have declared different types of variables without having to define them like C++.
Chain
String is an immutable object in python which means that once created, you cannot change its contents (for those of you who don’t understand this, then read this post and this lesson again). As said before, it doesn’t matter if you use single or double quotes. Jaw len
used to get the length of the string.
>>> var = "Hello, this is a string" >>> var 'Hello, this is a string' >>> new_var="Hello, this is a string" >>>new_var 'Hello, this is a string'
Integers and Reals
An integer in python can be either negative or positive because it doesn’t require any stipulation of variable data type like unsigned and signed integer in C.
>>> a_int = 5 >>> a_int 5 >>> a_float = 1.43 >>> a_float 1.43
As you can see, there is no need to declare variables, we can save a lot of time and quickly use new objects.
List, Set and Dictionary
List
List is a collection of homogeneous or heterogeneous data types which means we can store different data types in the same list. A list can contain duplicate data. To access the data in the list, you can use the index (index), ie the position of the element in the list.
>>> lists ["A","B","C","D"] >>> lists[0] # value atposition zero 'A'
Set
On the other hand, set is a mutable data type that can be used to store different data types but does not contain duplicated data.
>>> lists = ["A","B","C","D","A","B"] >>> set(lists) ["A","B","C","D"]
Dictionary
Dictionary is a hash table containing keys and their corresponding values. It has O(1) access time which means it takes a constant amount of time to retrieve the data. A value in a dictionary can be accessed from keys.
>>> dictionary {'Foo': 'Bar', 'Bacon': 'Fish'} >>> dictionary['Foo'] 'Bar' >>> dictionary['Bacon'] 'Fish'
Input
Syntax input
used to get input from the user in Terminal. By default, the input value will be a string. But you can also cast the data type from string to number by adding functions like int()
, float()
outside the jaw input()
.
#!/usr/bin/env python3 name = input("Enter Name: ") age = int(input("Enter age:" )) # Chuyển chuỗi sang số nguyên height = float(input("Enter height: ") #Chuyển chuỗi sang số thực
First, the variable name will take a string as input and age will take an integer as input while the height variable will take a real number as input. If any other type of object is imported, it will result in an exception error (Exception).
Operator
+
: Concatenate two strings or add two integers/reals.-
: Subtract integers/reals.=
: Used to assign a value to a variable.==
: Used to compare two similar variables with the same data type. For example 1 == 1, the result will be True.!=
: Used to compare two variables with the same data type. For example 1 != 1, the result will be False.%
: Divide by integer part of 2 numbers. Example 10 % 3 = 3.*
: Used to multiply a value. It is also possible to multiply strings. Eg:'Ad' + ' dep trai' * 5
the result will beAd dep trai dep trai dep trai dep trai dep trai
.>=
and<=
: Used to compare greater than or equal to and less than or equal to.and
: The AND operator will return True if all conditions are satisfied.or
: The OR operator will return True if only one of the conditions is satisfied.not
: Negation operator. For example, not True would be False.
Command flow control
If, elif and else . statements
These statements are called conditional statements. Used to test a condition then perform data processing.Example:
user = input("Enter Username: ") password = input("Enter Password: ") if user == "admin" and password == "123": print("Welcome Admin") elif user == "guest" and password == "guest": print("Welcome Guest") else: print("Wrong credentials")
user and password are all variables and receive input from the user using the function input
. In line 6, we have an if statement to check if user is equal to the string “admin” and password equals the string “123” or not. Commands and
is used to ensure that both conditions are True. On line number 8, we are checking if user and password is equal to “guest” or not. On line 10, the command print
will be run if the above two conditions are not satisfied.
for . loop
Commands for..in
is a loop statement, repeating the command as many times as the user wants.
num = 5 for i in range(num): print(i) # Will print 0,1,2,3,4
In line 2, there is a for..in statement that uses the function range
to iterate from 0 to 4. The for loop can be used to iterate over different data types like list, string, etc.
while . loop
The while statement allows you to repeat a block of statements as long as a condition is true. Eg:
num = 0 while num < 10: num += 1 print(num)
On line 1, we have the variable num assigned the value 0. Line 2 has a while statement that will be run until the num value is equal to or greater than 10 then stop. On line 3, we increment num by 1 after each iteration. So in line 4 we will get the value 10.
Jaw
Functions are reusable parts of the program. They allow you to name a block of statements, allow you to run the block by calling the specified name anywhere in your program, and unlimited number of calls.
The structure of the function:
def func_name(arg): -- your code -- return result
Key worddef
at the top to define a function. func_name
will be the name of the function. arg
is the parameter and return
for the final result. In python, a function is not required to have return
.
Exceptions –Exception
Exceptions occur when special situations occur in your program. For example, what if you’re reading a file and the file doesn’t exist? Or what if you accidentally delete it while the program is running? Such situations are handled using exceptions (Exceptions).
Example of a function call print
simple. What if we misspelled Print? In this case, Python will give a syntax error.
Traceback (most recent call last): File "<stdin>", line 1, in <module> NameError: name 'Print' is not defined >>> print("Hello World") Hello World
Handling exceptions
We can handle exceptions using the . statement try..except
. Basically, we put the usual statements in the block try
and put all the error handling cases in the block except.
try: text = input('Enter something --> ') except EOFError: print('Why did you do an EOF on me?') except KeyboardInterrupt: print('You cancelled the operation.') else: print('You entered {}'.format(text))
We put all statements that can generate exceptions/errors inside the block try
and then put handling commands for errors/exceptions in except
. Except
can handle a specified error or exception, or a list of errors/exceptions enclosed in parentheses. If no error or exception name is provided, it will handle all errors and exceptions.
Library module
The same way you reuse code like in functions. You can also reuse the code of another program in another file. It’s called a library module.
A library module can be used by another program to use its functionality. This is how we can use the Python standard library. First, we’ll see how to use the standard library modules.
import sys print('The command line arguments are:') for i in sys.argv: print(i) print('\n\nThe PYTHONPATH is', sys.path, '\n')
Access the sys library using the command import
. Basically, this means we tell Python that we want to use this module. The sys module contains functions related to the Python interpreter and the system and environment.
When Python executes the import sys statement, it looks for the sys module. In this case, it’s one of the built-in modules, and so Python knows where to look.
summary
Python is one of the most loved and popular languages. It is also used in many different areas such as web, app, security. You can read more python articles here. Also, to write Python code, I recommend using Sublime Text 3 or Visual Studio Code.