Python blockchain / According to python.org, “Python is an interpreted, object-oriented, high-level programming language with dynamic semantics. Its high-level built in data structures, combined with dynamic typing and dynamic binding, make it very attractive for Rapid Application Development, as well as for use as a scripting or glue language to connect existing components together.”
The Ultimate Guide to Python Blockchain: Part 1
Python is one of the most popular and powerful languages out there. Not only is it extremely beginner friendly, but it has also found applications in a lot of different areas as well. In fact, according to a survey by IEEE, Python happens to be the most popular language of 2017.
Image credit: Extreme Tech
Origins of Python
Guido van Rossum, a Dutch programmer, created Python back in 1991. Python is based on a simple philosophy: Simplicity and Minimalism. One of the more notable ways that they incorporated simplicity into their language is by using white spaces to signify code blocks instead of curly brackets or keywords.
Let’s see what this means by checking out a simple “hello world” program.
Yup, that’s about it!
The name of the language is derived from the famous British comedians Monty Python. The core philosophy of the language was summarized in the document “The Zen of Python”:
- Beautiful is better than ugly
- Explicit is better than implicit
- Simple is better than complex
- Complex is better than complicated
- Readability counts
At its very core, Python is an object-oriented, high-level programming language with an extensive library. Let’s go through what each of those terms means.
is an object-oriented programming (OOPs) language as opposed to a process-oriented one. Process-oriented languages like C utilized programs where a list of instructions that acted on memory.
OOPs, on the other hand, allows for the creation of a blueprint called “class” from where one can generate objects which can interact with each other. These objects execute the program.
Now, there are four pillars to OOPs:
Encapsulation is the idea of wrapping together data and function within one unit. The idea is to hide the initial state of the objects and to bind everything in a solid pack.
Abstraction means that a user can use the program without getting into the complications behind it.
Think of a car.
When you drive a car, all that you care about is putting your key in and maneuvering the vehicle in a way that you don’t hit anything else. You don’t care about how the engines work and how the ignition is burning your fuel.
Inheritance is one of the most important properties of OOPs.
Inheritance allows an object or a class to based upon another object or a class and retain some of its implementation. In most class-based object-oriented languages, an object created through inheritance acquires most of the properties and behaviors of the parent object
Polymorphism is the property by which an operator in the language can have more than one properties. The most famous example of this is “+”. Not only is it used as the mathematical addition operator, but it can also be used to combine two strings into one as well. This is called concatenation.
Eg. if we add two strings “Block” + “Geeks” the result will be “BlockGeeks”.
Low-Level vs High-Level
The level of the program is determined by its degree of interaction with the computer.
Low-Level languages are machine dependent languages which directly interact with the computer. Remember that computers can only understand instructions in the form of 0’s and 1’s. This is why these languages utilize these signals via Binary notation to interact with the computer directly.
It is because of this very reason, that low-level languages are also extremely difficult to learn for beginners, which is why they are not as popular as high-level languages.
Assembly Language is an example of a low-level language.
On the other hand, High-Level Languages are the machine-independent programming languages, which are easy to write, read, edit and understand.
So, while they may not interact with the machine directly and need to go through a compiler, they are extremely versatile and beginner friendly.
Examples of high-level languages are Python, Java, .Net, Pascal, COBOL, C++, C, C# etc.
The Python Library
One of the greatest strengths of Python is its super extensive library. The library contains built-in modules (written in C) that provide access to system functionality such as file I/O that would otherwise be inaccessible to Python programmers, as well as modules written in Python that provide standardized solutions for many problems that occur in everyday programming.
To make sure that internet facing applications are well-represented as well, many standard formats protocols like MIME and HTTP are supported in the library. It includes modules for creating graphical user interfaces, connecting to relational databases, generating pseudorandom numbers, arithmetic with arbitrary precision decimals, manipulating regular expressions, and unit testing.
As of March 2018, the Python Package Index (PyPI), the official repository for third-party Python software, contains over 130,000 packages with a wide range of functionality, including:
- Graphical user interfaces
- Web frameworks
- Test frameworks
- Web scraping
- System administration
- Scientific computing
- Text processing
- Image processing
What You Need To Start Off
- Firstly, you will need to go to python.org and download the latest version
- Secondly, you will need to download Visual Studio Code which you can do right here.
Before we continue, let’s just configure our Visual Studio.
Once you are done installing it, you will see this screen.
Now, go on File ->Open
After that, you need to create a folder. Let’s call this folder “Hello World”.
Once that is done, you will need to go to Extensions and install “Python”.
Note: The last Icon on the left toolbar (the square-shaped thing) is the Extensions button.
Alright, now that that’s done, let’s start with some coding!!
Note: Before moving onto Visual Studio Code, we will be working on “Terminal” for Mac and “Command Prompt” for Windows
Starting Things Off
The first line on your Terminal should look something like this (we are using a Mac air):
Right next to that line write “python”
X’s-MacBook-Air:~ Y$ python
Once you press enter, you will see this:
Python 2.7.10 (default, Aug 17 2018, 17:41:52)
[GCC 4.2.1 Compatible Apple LLVM 10.0.0 (clang-1000.0.42)] on darwin
Type “help”, “copyright”, “credits” or “license” for more information.
Basically, this means that you are now in and can start coding.
Let’s start off with simple numerical operators.
As you can see, pretty standard affair thus far. All the operations that we have done so far, follow the REPL formula.
R = Read
E = Evaluate
P = Print
L = Loop
2+2 is Read
The calculation of the result is Evaluate.
Printing of the result, i.e. 4 is Print
Loop basically means going back and starting all over again.
Let’s try to print “Hello World”.
>>> print(‘Hello World’)
See, pretty simple. You just use print() and put ‘Hello World’ inside in quotations. In the very next line itself, it will be printed. Also, note how we are not using a semi-colon to end our statements in python.
Data Types In Python
Alright, so now let’s talk about Data Types. In Python, there are 4 basic data types:
- Numbers (Integer and float)
Boolean values are a standard in programming languages. Boolean variables can only take in two values, True and False. They are really useful for condition-oriented coding such as if-else and loops.
As with all programming languages, python utilizes both integer and float data types. Integers are basically non-decimal numbers and floats are decimal numbers.
So, 3 is an integer while 3.4 is a float number.
Before we go any further, there are two interesting functions that you should know about, float() and int().
The float() function turns its parameter (the data within its brackets) into a float number.
So, float(5) turns into 5.0.
Similarly, int(4.6) turns into 4.
Notice that the number isn’t rounding off in the traditional sense. It just shaves off the decimal part.
Alright, let’s have some fun with these functions.
Suppose we have a boolean variable: a = True
If we do int(a) then we will get 1.
Remember that True = 1 and False = 0.
Similarly, float(a) will get us 1.0.
Finally, we have String.
A string is a data type used in programming, such as an integer and floating point unit, but is used to represent text rather than numbers. It is comprised of a set of characters that can also contain spaces and numbers.
They are declared like this:
You can use both single quotes and double quotes to contain your string. However, remember that you can’t use them both on the same string, eg. ‘Hello” will be an error.
Also, when you are using strings, be careful with apostrophes. Eg. ‘I’m a writer’ will be an error. You can correct this by putting a backslash before the apostrophe, like this: ‘I\’m a writer’
Alright, remember the int() and float() functions. Let’s see how those interact with string.
So, if n = ‘9’, and we want to add this with 1.
We can simply do: int(n) + 1 to get the output 10.
Conversely, if we do float(n) then the output will be 9.0.
Remember, during all this time, ‘n’ still remains a string variable. We are merely using an instance of the string to do our mathematical operations. Let us show you that in the terminal.
However, if n had a floating value like ‘4.5’ and we try to use the int() function then we will get an error. This happens because the content of the string itself is a floating point variable.
Let’s have some more fun with strings.
Remember, that one of the properties of object-oriented programming is Polymorphism.
So, let’s try concatenation.
The “*” can also do some interesting stuff with string variables.
As you can see, we multiplied name by 10 and we got the value of name 10 times.
Operators are tools that you can use to manipulate a particular value or operands. The three most common operators that you will find in python are:
Boolean operators deal with values and operands and give boolean outputs i.e. True or False
The logical operator compares two conditions and gives a Boolean result.
Functions are the backbone of modern programming. So far, whatever programming we have done is pretty basic. However, programs can have 100s of lines of code which can get pretty hard to keep track of.
This is why we use programs, which basically acts like modules in that particular program.
Let’s take an example in order to understand the significance of functions.
Suppose you are writing a huge novel with no chapters at all. If you have described something before in the book, chances are, that if you have to cite it again, you will have to repeat some of the passages.
The problem with this is that it leads to redundancy, which is a waste of energy, money, and time.
Now, what if we actually segmented the book into several chapters. It brings in a lot of structure and neatness to the whole presentation of the book. So, if we want to refer back to something that we have mentioned earlier, we can simply let the user know which chapter number they can refer to.
In this analogy, the book is the program and the chapters are the functions.
So, how exactly do you define a function in python? Well, let’s take a look.
For these programs, we are going to use Visual Studio Code.
Just open your VSC and the folder that we made earlier. After doing that, click on this button to open a new file:
Name your file whatever you want, but be sure to end it with a “.py”. We are going to name our file “app.py”.
Ok, so let’s try out our first function!
As you can see, we begin the function definition with the “def” keyword. After that, we have the name of the function followed by the brackets and a colon.
After that, unlike other languages, python doesn’t utilize curly brackets to define the function body. Instead, all that you need to do is to indent a little bit and add the body. VSC does this for you automatically.
After the function definition, you just simply call the function by typing “greet()”.
Ok, so after you write the program, be sure to save it. After that, we are going to open the terminal by clicking here:
When you open the terminal, you will see something like this:
Right now just type in “python filename.py”.
In this case, our file name is “app” so we will type, python app.py.
The moment you do that, as you can see above, the program will print “Hello”.
Now, let’s bring in some arguments into our function.
Arguments are the parameters that go inside the function. So, let’s go back to our greet function and add some extra elements:
def greet(first_name, last_name)
In this case, the first_name and last_name are the arguments that are going inside this function. So, when you call the function this time, you need to pass the parameters as well, which will look like this:
The entire program looks like this:
So, when you execute this program, the output will be:
Conditional statements are a staple in all programming languages, and python executes that with if-elif-else statements. Elif is an abbreviation of “else-if”. The syntax usually goes like this:
If condition 1:
elif condition 2:
So, what is happening here?
- If condition 1 is correct, then statement 1 will get executed and then the code will jump to statement 4 to execute it.
- If condition 2 is false then the code moves to condition 2. If condition 2 is correct is correct then statement 2 gets executed, followed by statement 4.
- If none of the conditions are correct, then statement 3 gets executed by default followed by statement 4.
In the hypothetical code that we have given above, statement 4 does not belong to any of the conditions, which is why it gets executed by default at the end.
Ok, so now let’s check a simple program which uses only if.
In this program, we are simply checking if the number is less than 6 or not. If it is then we are going to print the result. Since the condition is met, the program outputs the statement in its terminal.
Ok, now let’s take this to another level and bring in some elifs. Check out the following piece of code:
What you have here is pretty much the same code as before.
Ok, so now, we are going to take it to the last level. Let’s introduce a final else statement.
So, we have three conditions here:
- First one checks if the number is greater than 6 or not
- The next on checks if the number is less than 4
- Finally, if all the conditions fail, then the else block gets activated and prints that the number is 5.
This is exactly what happens in out code as you can see in the terminal below
#2 Tertiary Statements
Finally, we have tertiary statements. Check out this code:
age = 21
message = “You are eligible” if age >= 18 else “You are not eligible”
You see that statement?
“You are eligible” if age >= 18 else “You are not eligible”
This is called a tertiary statement, which follows this format: “Statement 1” if Condition else “Statement 2”
Basically, Statement 1 will be activated only if the condition is true, otherwise, Statement 2 is activated.
Finally, you have loops. Loops are an integral part of programming and are used when the repetition of a particular task is required. Python’s loops are actually pretty interesting and add a whole new dimension to your coding.
#1 For Loops
For now, let’s check out the basic for loop:
for num in range(3):
Ok, so what is happening here?
range(n) will give you numbers that go from 0 to n-1. So, in this case, it goes from 0 to 2. The num variable is going to assume the value of the range at each run through. So, if you print “num”, this is what you will be getting:
“num” takes up al the values from 0 to n-1 in each iteration.
Oh and this is not just limited to numbers. We can make this loop with strings as well.
for x in “PYTHON”:
This will print the following:
As you can see, x takes up each and every character in the string.
#2 While Loops
There is another kind of loop out there called the “while” loop.
number = 100
while number >= 1:
number //= 2
So, what is happening here?
We are running the loop until the number is greater than or equal to 1. When we do number //=2 we are basically doing number = number//2.
Let’s see what this prints out:
Playing Around with Loops
#1 Combining Loops with If-Else
The first thing that we are going to do is to combine loops along with the if-else statements.
x = 100
for number in range(3):
if x > 1:
If we execute this, the output will be like this:
Ok, let’s change this up a bit. We are going to add something to this code.
x = 100
for number in range(3):
if x > 1:
What’s the difference?
You see that one single word added to the code? The “break” keyword helps the compiler to break out of the code. Hence in the above code, “positive” is printed only once and then the compiler breaks out.
#2 Nested Loops
Nested loops are basically loops within loops. Here check this out:
for x in range(5):
for y in range(3):
So what happened here?
We have a x loop and a y loop that runs inside it. Now, let’s print the result in the terminal and see what we get:
Python blockchain: Conclusion
Let’s stop here for now.
We have given you the basics of the Python language. We suggest that you use the code to fiddle around a bit and get more comfortable. In the next part, we are finally going to get started on our blockchain.
Thanks, it’s a very fast way to start with Python!
Thank you for introducing Python in your curriculum.