Python from zero to hero

- How to roll back an Oracle Database using a restore point in a Data Guard environment - 28 April 2025
- How can we increase performance on Oracle GoldenGate Replicat target with parallelism? - 19 March 2025
- How to create users in databases that belong to a SQL Server Always On Availability Group - 10 February 2025
In this not TLDR article (I hope) we will go over all the basic concepts and constructs of the Python scripting programming language.
H Python it is an interpreted language and not compiled which means that the translation of the program into machine language is not done all at once when we choose to compile but you run directly and translate directly from the interpreter per command line.
Shebang line
At sheband line which should be the first line of our code, we declare the path where Python (the interpreter) is installed.
#!/usr/bin/python3.6
At Python we define variables without having to declare them with their datatype. With the function print we display either the variable or directly what we have assigned to it.
a=2+3 print(type(a)) print(a)
<class 'int'>
5
When we set to a variable with quote it is defined as string.
a='2'+'3' print(type(a)) print(a)
<class 'str'>
23
When we use it print function we can use the parameter sep to separate the data from each other or the end to be added to the end of the line.
print('0','1','2','3',sep='-') print('0','1','2','3',end='-')
0-1-2-3
0 1 2 3-
Loops
Let's go to examples of loops with for and while. Don't forget that the range starts at 0 and goes up to the value we set excluding this value.
for i in range(0,3): print(i)
0
1
2
i = 0 while i < 3: print(i) i = i + 1
0
1
2
Data structures
In Python we use 3 structures data lists, tuples and dictionary. We can also use combinations such as lists or a dictionary containing tuples.
Lists
H list is an array of data that allows changes such as sorting, removing or adding data.
Defined as =[a,b].
list = ['μπανάνα','μήλο','κεράσι','φράουλα'] print(type(list)) print(list)
<class 'list'>
['μπανάνα', 'μήλο', 'κεράσι', 'φράουλα']
We can choose from which value to which we want to fetch with the first value being 0
print(list[1:3])
['μήλο', 'κεράσι']
We can also bring them in reverse order
print(list[::-1])
['φράουλα', 'κεράσι', 'μήλο', 'μπανάνα']
We can remove and add data.
list.append('ανανάς') list.remove('φράουλα') print(list)
['μπανάνα', 'μήλο', 'κεράσι', 'ανανάς']
We can put it in alphabetical order.
list.sort() print(list)
['ακτινίδιο', 'ανανάς', 'κεράσι', 'μήλο', 'μπανάνα', 'σύκο']
Tuples
That tuple it is like a list with the difference that it is immutable, i.e. it does not accept changes.
Defined as = (a,b)
tuple = (1, 2, 3, 'παπάκι') print(type(tuple)) print(tuple)
<class 'tuple'>
(1, 2, 3, 'παπάκι')
Dictionaries
That dictionary it is like a list with the difference that its structure is divided into key and value. The key is like the title of the field and must be unique.
Defined as ={key:value}.
dictionary = {'onoma':('Stratos','Nikos','Maria'),'epitheto':('Matzouranis','Georgiou','Papa')} print(dictionary)
{'onoma': ('Stratos', 'Nikos', 'Maria'), 'epitheto': ('Matzouranis', 'Georgiou', 'Papa')}
With the command.key we can see the keys it has.
print(dictionary.keys())
dict_keys(['onoma', 'epitheto'])
We can print all the names belonging to the name key:
print(dictionary.keys())
dict_keys(['onoma', 'epitheto'])
We can print all the names belonging to the name key:
print(dictionary['onoma'])
('Stratos', 'Nikos', 'Maria')
We can only print the third name:
print(dictionary['onoma'][2])
Maria
or all prices:
print(dictionary.values())
dict_values([('Stratos', 'Nikos', 'Maria'), ('Matzouranis', 'Georgiou', 'Papa')])
Create and view a multidimensional array
Let's do something more advanced, a 4×3 list printed as a table. To achieve this we should use loops like below:
z = [ [i for i in range(4)] for j in range(3) ] for rows in range(len(z)): for col in range(len(z[0])): print(z[rows][col],end='|') print('\n-----------')
0|1|2|3|
-----------
0|1|2|3|
-----------
0|1|2|3|
-----------
Functions
A piece of code that you only run when we call it is called function. The function can accept parameters that will affect its execution. Let's look at an example:
def Dokimifunction(onoma,posa=1): timi = onoma+'!'*posa return timi;
This function accepts as a parameter a name and as a second parameter a number, which number is the number of times the exclamation mark will appear at the end. In the parameters we can give a default value so that if it has not been declared it will apply:
*if we didn't do it when we didn't define the number, it would return an error.
xristis='Κώστας' print(Dokimifunction(xristis)) print(Dokimifunction(xristis,5))
Κώστας!
Κώστας!!!!!
Error Handling
Let's see what the value of the "timi" parameter defined in the function is:
print(timi)
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-226-e0b6617a2c0c> in <module>
----> 1 print(timi)
NameError: name 'timi' is not defined
Oh... the variables inside a function by default are not global, so an opportunity to see how it works error handling:
try:
print(timi)
except:
print("Oops! Δεν υπάρχει...")
Oops! Δεν υπάρχει...
Classes
To be able to inherit an object with a set of properties and methods from an initial design we need classes.
The class consists of one constructor called init and passes its properties to the object being created, a constructor for the parameters called self and from there on we can add other parameters and other functions that it will contain.
Let's build a quick class that can add and display two numbers:
class Prosthesi: a = 0 b = 0 apotelesma = 0 #To def __init__ ονομάζεται constructor και χρειάζεται πάντα για να δημιουργηθεί το object. #self είναι ο constructor της αρχικοποίησης των παραμέτρων def __init__(self, timi_tou_a, timi_tou_b): self.a = timi_tou_a self.b = timi_tou_b def show(self): print("ο πρώτος αριθμός = " + str(self.a)) print("ο δεύτερος αριθμός = " + str(self.b)) print("η πρόσθεση = " + str(self.apotelesma)) def ipologise(self): self.apotelesma = self.a + self.b
To make the object with the legacy of the class for the numbers 13 and 28 we execute the following:
mathimatika=(Prosthesi(13,28))
With the name of the function we can call it:
mathimatika.show()
ο πρώτος αριθμός = 13
ο δεύτερος αριθμός = 28
η πρόσθεση = 0
We see that the addition returned zero as the function that does the calculation first was not executed. Let's go again:
mathimatika.ipologise() mathimatika.show()
ο πρώτος αριθμός = 13
ο δεύτερος αριθμός = 28
η πρόσθεση = 41
We see this time it worked fine.
Modules
We can import a package of functions, classes and variables called module with the import command.
Let's see how we introduce a builtin module for mathematics and call a function to calculate pi:
import math print(math.pi)
3.141592653589793
We can also load only specific functions from the module.
We can also define an alias for it so that we don't have to call it with the whole name of the module plus the function:
from random import randrange as rr #random.randrange(100) είναι το ίδιο με το από κάτω. rr(100)
How to install a module
To install a custom module from the internet the command is pip install:
pip install pandas
I hope you endured until the end, in other articles we will see examples with custom libraries where its real capabilities are hidden.