NAVIGATE

RESOURCES

CHEATSHEETS

INFO

Python: a quick overview

Python is a very common scripting language so, if you don't know it, you can find here an introductory article to learn something about it. Learn Python to make things simple!

Intro

img
Python logo

Python scripting language was developed by Guido van Rossum and published for the first time in the 1990s, although the first 2.x version was released in 2000. It is a simple and reliable language, easy to learn and to read (it's probably the most readable language ever created - so simple to be often used as pseudo-code), usable in many many fields, from computational maths to web applications, from medicine to finance, from engineering to game development, from big data processing to artificial intelligence (...).

It has the following characteristics

  • Interpreted: Python scripts are not converted directly to machine code but toan intermediate bytecode file, then read and executed by the interpreter
  • High-level: it abstracts from the computer-related programming features since the interpreter manage them automatically
  • Garbage-collection: Python automatically manages memory so you don't have to manually allocate and free it since the interpreter will do it for you
  • Dynamically-typed: you don't have to define variable types, Python interpreter automatically understands it
  • Multi-paradigm: it supports general, imperative (procedural, object-oriented), declarative (functional) programming paradigms so you can use the style you prefer according to what you have to do

Just an important note: today, two versions of Python are currently used around the world - Python2.x and Python3.x - but they are not fully compatible: a code written in Python3.x will not work with a Python 2.x interpreter and vice versa!

Installation

Windows installation

Linux installation

First of all, if your system is not up-to-date, I suggest you perform a full system upgrade.

0
sudo apt update && sudo apt upgrade

To install latest Python 2.x package open the terminal and type

0
sudo apt install python2

then type your password and press enter. To install the latest Python 3.x package open the terminal and type

0
sudo apt install python3

then type your password and press enter. I suggest to install both versions.

Python main practical features

A Python script structure can change a lot according to the programming style you adopt. However here you can find the most basic aspects that never change.

Variables

As already said, Python is dynamically typed. The interpreter automatically understands the variable type by reading the right-hand side of an assignment operation.

0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# Here some examples
myIntVariable = 435                             # Normal integer variable
myFloatVariable = 34.465                        # Normal float variable
myStringVariable = "I am a string!"             # String variable - you don't have to set length nor mem alloc
myBoolVariable = False                          # Boolean variable
myListVariable = [3, 4, 5, 14232]               # List of integer values
myComplexListVariable = [3, 2.546654, "String"] # Mixed list! This feature is great!

# Also reassignment is dynamic
myIntVariable = "Now I'm a string!"
myComplexListVariable = [ ['c', 3454] , [43.54, "Another string"] , [22, True] ]
myStringVariable = ()

# Complex numbers
myComplexNumber = 0+1j                          # Yes, Python can manage complex numbers too!

Variables scope

Python variables scope is pretty intuitive; however this feature is briefly described below:

  • Variable defined outside every function or class: this is a global variable if and only if inside functions and classes there is no other variable with the same name
  • Variable defined outside every function or class: this is a global variable if and only if that variable is not overwritten inside a function or class; if it is, the inner one will be a variable different from the outer one
  • Variable defined inside a function or class: these variables are local and cannot be accessed from outside

Let's see some examples (syntax for functions and classes is explained after in this article)

0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
myVarA = 55
myVarB = 71
myVarP = 3.14

def myFunctionA():
    localVarQ = "PI is: "
    print(localVarQ+str(myVarP))      # myVarP is accessed as a read-only variable so it is linked to the outer one

def myFunctionA2():
    myVarP = 3.141592                 # MyVarP is accessed in writing mode so myVarP in myFunctionA2 is NOT the 
    localVarQ = "PI is: "             # same myVarP of the outer scope
    print(localVarQ+str(myVarP))

def myFunctionA3():
    global myVarP                     # The 'global' keyword makes the function understand that myVarP inside the  
    myVarP = 3.14159265358            # myFunctionA3 scope is the same as the outer one! Here the OUTER variable is accessed and modified
    localVarQ = "PI is: "
    print(localVarQ+str(myVarP))
    
def myFunctionB(myVarA, myVarB):
    print(str(myVarA*myVarB))         # This two variables are local and not related to the outer ones

class myClass:
    myVarA = 42                       # These two variables are locally defined
    myVarB = 2.71828182
    def printOuterValues(self):       # Variables without 'self.' are the outer ones
        print("Outer Values: ",myVarA,myVarB)
    def printInnerValues(self):       # Variables with 'self.' are the inner ones
        print("Inner values ",self.myVarA,self.myVarB)
    
print(myVarA,myVarB,myVarP)
myFunctionA()
print(myVarA,myVarB,myVarP)
myFunctionA2()
print(myVarA,myVarB,myVarP)
myFunctionA3()
print(myVarA,myVarB,myVarP)
myFunctionB(54,70)
print(myVarA,myVarB,myVarP)
myObj = myClass()
myObj.printOuterValues()
myObj.printInnerValues()
print(myVarA,myVarB,myVarP)
myObj.myVarA = 105
myObj.myVarB = 1
myObj.printOuterValues()
myObj.printInnerValues()
print(myVarA,myVarB,myVarP)
    

The notation for classes is explained in the next chapters.

Basic operations

Arithmetic and logic operations

Casting

You can cast data whenever possible, using the related cast operator.

String manipulation

Functions

If you have a repetitive portion of code, then it's probably good to write it only once and then reuse it when it's required. So let's learn how to write a function: an example is the fastest way to start:

0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
# Here I define two functions and I recall one of them in the main script when I need it

# This function returns the area of a trapezium
def trapzAreaFunction(bmin,bmaj,step):
    return (float(bmin)+float(bmaj))*float(step)/2.0

# This function returns the integral of a y=f(x), given y and x as two lists
# It is based on the previous function for the single trapezium area calculation
def integralCalcFunction(y,x):
    intsum = 0
    # Check if the two lists have the same length
    if len(x) != len (y):
        return 0
    l = len(y)              # len is a built-in Python function to know the number of elements in a list 
    for i in range(0,l-1):  # range is a built-in Python function that returns a list of numbers
        intsum += trapzAreaFunction(y[i],y[i+1],x[i+1]-x[i])
    return intsum

Note that in Python you can define functions inside functions! This is a great feature that helps to prevent calling a function from a scope it should not be called. See the example below:

0
1
2
3
4
5
6
7
8
9
def functionA(x,y):     # This functionA...
	return x+y
	
def functionB(k,l):
	def functionA(x,y):     # and this one are not the same; the latter is local to functionB only
		return x+y-y**2
	return functionA(k,l)
	
print (functionA(45,11), functionB(45,11))

The first functionA defined is valid and callable from everywhere in the script, its scope is global. The second functionB contains another functionA which is not the same as the outer one: x and y defined as parameters in the first functionA are not shared with the second one since they are completely different functions. functionA defined inside functionB can be called from the inner functionB scope.

Classes

Libraries

Libraries! Python has many of them! If you think of a problem, probably there already exists a Python library that solves it! The most important ones you should know (use them rather than writing a code from 0 since they are optimized) are listed below; they come with the main Python installation (they are part of the Python Standard Library), so you don't have to install anything else.

When you want to use a Python library, add to the beginning of your script file one of the two lines, according to the type of import you want to do.

0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import math             # If you want to refer to 'math' library functions as math.<funct name>
from math import *      # If you want to use directly <funct name> along your code
import math as m        # If you want to address the library with the name you prefer (alias)

# Example of first import mode
freq = 1000
timeInst = 0.4
x = math.sin(2*math.pi*freq*timeInst) # pi is a constant and sin is a function, both defined in 'math' library

# Example of second import mode
freq = 1000
timeInst = 0.4
x = sin(2*pi*freq*timeInst) # pi is a constant and sin is a function, both defined in 'math' library

# Example of third import mode
freq = 1000
timeInst = 0.4
x = m.sin(2*m.pi*freq*timeInst) # Here 'm.' was used instead of 'math.' since the library was imported with an alias

string

Useful library for string manipulation.

struct

In Python, all variables are dynamically allocated and the programmer can't play with memory, manage data in binary mode perform operations on bits and so on. If you need access to data structures with such fine grain, you should consider using the 'struct' library: it helps to split and compose data structures as you want down to the single bit.

datetime

math

Libraries contain everything you need to deal with mathematics and advanced operations. Here you'll find constant definitions like pi, e, NaN, Inf and many useful functions to round, get the absolute value, perform trigonometric operations, deal with logarithms and exponentials...However, if you want to expand from R to C, use the next library, then.

cmath

Extends operations to the set of complex numbers.

random

os

multiprocessing

threading

socket

The right library for your low-level network programming. It resembles the C management of socket (obviously, in Python everything is simpler) and I recommend starting with this one if you want to develop some kind of application that communicates through the internet or ethernet.

Important aspect: speed!

So everything is perfect with Python (easy, high-level, readable), so why isn't it used everywhere? It's slow! Very slow! Ultra slow! So slow that if you compare a C code and a Python code executing the same algorithm, you will see that the Python code is 10 to 80 times slower than the C code. Moreover, it requires more resources since it is interpreted (even if it's translated to bytecode before execution). Don't trust me? Let's try! Here you can find two equivalent codes in C and Python: they find the highest prime number in the given range (you can change 100001 as you desire). Compile the C code then run them and you'll see the huge difference!

0
1
2
3
4
5
6
7
8
9
10
11
12
13
# Python 2.7 code

highestPrime = 0
for i in range(2,100001):
	flag = 0
	for j in range(2,i):
		if (i%j == 0):
			flag = 1
			break
	if (flag == 1):
		continue
	else:
		highestPrime = i
print highestPrime

Now the C code

0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
// C code

#include <stdio.h>

int main(){
	int highestPrime = 0;
	int flag = 0;
	for(int i=2; i<100001; i++){
		flag = 0;
		for(int j=2; j<i; j++){
			if(i%j == 0){
				flag = 1;
				break;
			}
		}
		if(flag == 1){
			continue;
		}
		else{
			highestPrime = i;
		}
	}
	printf("%d\n",highestPrime);
	return 0;
}

Since this is an important aspect, I've dedicated an article to Python computational efficiency and comparison with other compiled and interpreted languages here.

Conclusions

Now, you should have all the basic information to start writing Python scripts. Whenever you need to automatize a calculation or something else, consider using it, since it also has a big support community and it's full of resources on the Internet.

Share this page

Whatsapp Facebook LinkedIn Reddit Twitter Mail

Comments

Please, remember to always be polite and respectful in the comments section. In case of doubts, read this before posting.

Posted comments ⮧

Comment section still empty.

If you liked

🍵
♥