The logic behind Python
First, get in your mind that Python is easy. There is no need to have a Computer Science degree to understand Python code and write Python code. It is very close to spoken language, but it just had to be formalized a bit so that every computer interprets it the same way.
Open a Jupyter Notebook, and we’ll dive in the basics of Python programming.
To illustrate how easy Python programming can be, say that you want your computer to print the content “Hello world” when you run the cell. How to do that?
Well, if we write the instruction, it would be something like
print Hello World!. It’s almost that, but I need to say where the string to print starts, and where it ends. Therefore, simply add quotes:
print "Hello World!"
Nice, if you execute that, you’ll get an error. Since Python 3, the print statement must have parenthesis. Simply adapt it:
It’s that easy. Run this cell, and it will display under “Hello World!”. Learning Python (as well as many other programming languages) is just about learning a syntax. The logic behind most languages remains the same.
Now, printing information is cool, but we will start defining variables.
var_a = 1 var_b = 1.4 var_c = "Hello World!"
We define a name, the name of the variable, and attach to it a value. You can naturally read: var_a equals 1.
Another example of this logic is the if-statement:
if var_a == 2: print(var_a) else: print(var_b)
We will come back to this later, but to know what this does, simply read it. If var_a is equal to 2, print var_a, else, print var_b. This is straight forward. Now that you get the logic, let’s dive in the code.
Python data types do not have to be declared, they are infered automatically. You create a variable, which is an object that takes a value, and can be re-used or modified. The data types can be:
- a string :
var_a = "Hello World!"
- an interger :
var_a = 1
- a float :
var_a = 1.02
- a boolean, takes values True or False :
var_a = True
You can give different names to your variables, and try to make them expressive. For example:
size_house = 120.35 nb_rooms = 5
You can convert one type into another using type converter:
size_integer = int(size_house)
This will only keep the integer part for example. You can also transform a integer into a float:
float_nb_rooms = float(nb_rooms)
And transform an integer into a string:
str_nb_rooms = str(nb_rooms)
Some transformations will of course give you error, when you try to cast a string into an integer and the string itself is not a number.
You can perform operations on these variables once defined, such as addition, substraction, multiplication, division, exponent, modulo…
Take for example:
a = 5 b = 2
a + b
a - b
a * b
a / b
a ** b
If you found the article useful or see ways in which it could be improved, please leave a comment :)
Like it? Buy me a coffee