Python tutorial

This is a short tutorial on the basic use of the Python programming language, more specifically, Python 3. The information contained here is more or less a TL;DR version of the actual Python tutorial available on the official Python website.

It is NOT intended to be an indepth guide about all of the features of the language but much rather an overview of the basic features which you can check to learn how to make simple scripts. This document is intended for people coming from another language and looking to learn Python quickly.

This document assumes that you already know the basic concepts of computer programming. (For example, I won’t explain what is a loop, but tell you how to do one with the Python language)

For the complete documentation please go to the official Python website, where you’ll be able to learn more about the language itself and the philosophy behind it.

Even if I tested each instruction and reviewed the document multiple times, there can still be some errors left, so if you find any information that isn’t true or a code segment that doesn’t work, please send me an email at contact@lekrock.com I will correct it.

Important notes

The first line has to specify where the Python executable is (like in Unix scripts).

#!/usr/bin/python

or

#!/usr/local/bin/python

The file extension of a Python script is “.py”.

In the Linux/Unix environment, the script has to be set as executable (just like any Bash script).

chmod +x myscript.py

or

chmod 755 myscript.py

Python uses indentation instead of brackets, the code inside a block has to be indented to be considered part of the block, this is also true for interactive mode. (The fact that there is a space in front of the first line of each code block of this tutorial seems to be a visual bug, so you do not have to do it in your own scripts)

# This is a function
def myFunction():
    print('Code goes here')    # This line is indented so it is a part of the above fonction
# This is a function call
# The function call is not part of the function definition because it is not indented
myFunction()

Python is case sensitive, so “var” and “Var” will be two different variables.

var = 1
Var = 2

print(var, Var)

# Will output (without quotes): "1 2"

In array-like structures, the first index is 0 (zero).

myString = "abc"
print(myString[0])

# Will output (without quotes): "a"

Having a trailing comma at the end of a serie of values is accepted by the interpreter.

myList = ['a', 'b', 'c',]

Interactive mode

Calling the Python executable from a terminal will start Python in interactive mode.

Interactive mode allows you to type and run Python commands at will. It can do pretty much anything that would be possible within a script, including multi-line commands, functions, loops and classes. The indentation rules must be applied in the same way as in a script.

Basic code structures

A comment starts with “#”. Note that the space or tabulation character is NOT required between the “#” symbol and the beginning of the actual comment, but every comment in this tutorial will have one to make the comments more easily readable.

# This is a comment

Arithmetic operators:

  • Addition: +
  • Substraction: –
  • Multiplication: *
  • Division: /
  • Floored quotient: //
  • Reminder: %
  • Power: **

Primitive data types (the most commonly used):

  • Integer
  • Float
  • Boolean
  • Bytes
  • String

Value assignment is done with “=”, as you would probably expect.

v = 1 + 2

Multiple assignment is also possible.

v1, v2 = 1, 2

The absence of value, often defined by “null” or “nil” in other languages, is defined as “None” in Python.

Printing text in the terminal is done using the “print()” function.

print("Hello world!")

Strings

Strings can be defined with both single (‘) and double (“) quotes.

The escape character is the backslash (\) with both single and double quotes.

Strings can be concatenated with “+”.

language = "Python"
print('I\'m coding with ' + language + "!")

# Will output (without quotes): "I'm coding with Python!"

Substrings

Getting a substring is done by using slicing.

language = 'Python'
print(language[2:4])

# Will output (without quotes): "th"

String length

The “len()” function returns the length of a string.

 if len(language) == 0:
     print("Empty string!")

Characters

Characters are strings with a length of 1.

Any character can be accessed by referring to its corresponding index inside the container string.

language = 'Python'
print(language[1])

# Will ouput (without quotes): "y"

Conditions and structures

Zero (0) is considered as “False” and every other value is “True”. Note that when using the two boolean values by their “name” (True and False), their first letter has to be capitalized.

Comparison operators:

  • Less than: <
  • Less than or equal: <=
  • Greater than: >
  • Greater than or equal: >=
  • Equal: ==
  • Not Equal: !=

It is possible to compare objects with “is” and “is not”, instead of “==” and “!=”.

Comparisons can be combined with “and” and “or”.

The result of a comparison can be assigned to a variable.

The “not” keyword is used to negate a boolean value.

myValue = True
if myValue == True:
	myValue = not myValue

# myValue will become "False"

if

The “if” statement is similar to what it is in other common languages.

x = 0
if x == 0:
    print('x is equal to zero')
elif x > 0:
    print('x is positive')
else:
    print('x is negative')

# Will output (without quotes): "x is equal to zero"

Switch

This statement doesn’t exist in Python, a combination of if/elif will be required to simulate the effect.

General information about loops

  • It is possible to break out of a loop with the “break” keyword.
  • The “continue” keyword allows for stepping directly to the next iteration.
  • The “else” keyword allows to execute code at the end of a loop that didn’t end with a “break”.

while

The while statement works pretty much the same as the common while in other languages.

i = 0
while i < 10:
    print(i)
    i += 1

for

The for statement works as a “for each”.

items = ['this', 'is', 'a', 'sequence']
for item in items:
    print(item)

Though it is possible to use the range() function to iterate over a serie of numbers.

for i in range(10):
    print(i)

pass

This instruction does absolutely nothing, it can be used where a statement is required but no action is needed.

Functions

General information

All functions return a value even if there is no return instruction, in this case the value would be “None”.

def myFunction(word):
    print(word)

Python functions can return multiple values, which will have to be separated by commas in the “return” instruction. On the receiving end of the function call, you can either assign the returned values into separate variables, or in a single tuple.

def plusAndMinus(n1, n2):
	return n1 + n2, n1 - n2    # This function returns the result of an addition and a substraction

r1, r2 = plusAndMinus(5, 3)    # Here we use separate variables
t1 = plusAndMinus(4, 2)        # Here t1 will be a tuple containing both values

A function can be renamed by assigning it to a variable (which is useful when using modules).

useful = myModule.myUsefulFunction

Arguments

They are put inside the parentheses of the function signature like in most languages.

It is possible to set a default value by assigning a value to the argument in the definition. Once you put a default value for a parameter, all the following parameters will need to have one too.

def myFunction(message='This is the default message.'):
    print(message)

Sequences

General information

Sequences are array-like containers, there are multiple types of sequences in Python and each one of them has specific features.

The “in” and “not in” keywords allow for searching inside sequences for the presence and absence of an item.

myValue = 'value'
if myValue in ('word', 'thing', 'value'):
    print('Found!')

Slices

A slice is an interval of values inside a sequence. It eases the selection of mutliple values at once. The next example is just a simple overview, please refer to the official documentation to see more advanced uses of slicing.

The start index is inclusive and the end index is exclusive (will not be included in the returned values).

myLetters = ['a', 'b', 'c', 'd', 'e']
myLetters[1:3]

# Will output: ['b', 'c']

Negative indexes

Using a negative number as a sequence index will return the corresponding item starting from the end of the sequence. It also works with slices.

Sequence conversions

  • A sequence can be converted to a tuple using the “tuple()” function.
  • A sequence can be converted to a list using the “list()” function.

Lists

A list is a mutable comma-separated group of values.

myList = ['this', 'is', 'a', 'list']

Characteristics of a list:

  • Can contain values of the same type
  • The “len()” function returns the length of the list
  • Items are added with the “append()” function
  • Can be nested in other lists
  • Can be used as a stack using “append()” and “pop()”

The “del” keyword can be used to delete an item at a precise index.

del myList[0]

Tuples

A tuple is an immutable comma-separated group of values.

myTuple = 'this', 'is', 'a', 'tuple'

Characteristics of a tuple:

  • Can contain values of different types
  • Values can be nested
  • Can contain lists (which are mutable)

Sets

A set is a collection of items that has no duplicate values.

Characteristics of a set:

  • Can be created with the “set()” function or with {}
set1 = {'this', 'is', 'a', 'set'}

set2 = set(['this', 'is', 'another', 'set'])
  • The content is mutable
  • Can be used to filter duplicate values from another sequence
  • Supports operations like “union”, “intersection”, “difference” and “symmetric” (with the appropriate operators)

Dictionaries

A dictionary is a sequence of key-value pairs.

Characteristics of a dictionary:

  • The index can be of any immutable type (even tuples if their content isn’t mutable types)
  • Keys have to be unique
  • Create an empty dictionary with “{}”
  • Items and their indexes can be deleted with the “del()” function
  • A list of keys can be obtained with the “keys()” function
  • Use the “in” keyword to find a key
myDictionary = {1: 'first', 2: 'second'}

Objects

The methods of an object are called using the dot notation.

print(person.name)

with

The “with” block can be used to work with resources, it will take care of releasing them at the end of the block no matter what the outcome is (on success and failure).

with open('/home/someone/myfile.txt', 'r') as file:
    fileContent = file.read()

Documentation strings

Python provides a way to self-document code, and it is done using the triple quote (“””).

The documentation string should be placed at the beginning of the block. The first line should describe what the code does in a short and precise way.

If there is a need for more than one line, the second line has to be empty. The next lines will be a more indepth explanation of the code.

The “__doc__” attribute contains the text of the documentation string.

def myFunction():
    """This function is an example.

    This is the rest of the text about the function
    if there is a need for it.
    """
    print('This is an example.')

print(myFunction.__doc__)

Modules

Modules can contain code that is intended to be used often in multiple scripts.

Modules are in a separate Python file and also have the extension “.py”.

There is a list of useful modules at the end of this tutorial.

Modules are imported by using the “import” command and following it with the name of the needed module.

import myModule

Module imports should be placed at the beginning of the file.

The content of a module is accessible with the dot notation.

myModule.myUsefulFunction()

Inputs and outputs

Strings

It is possible to format strings with the “format()” function.

print("I'm using the {0} function!".format('format'))

# Will output (without quotes): "I'm using the format function!"

The column alignment of strings can be adjusted using the “ljust()”, “rjust()” and “center()” functions.

Conversion to string

“str()” will convert an already human readable value to a string.

“repr()” will convert a non-human readable value (such as binary) to a string readable by the interpreter.

Data conversions

To convert a string to a number, call the number’s type as a function and pass the string as first argument.

aString = "8"
anInteger = int(aString)

To convert a number to a string, call “str()” and pass the number as first argument.

aString = str(anInteger)

Files

The “open()” function opens a file with a filename and the open mode as parameters.

myFile = open('/home/someone/somefile.txt', 'r+')

Open modes are as follows:

  • “r” for read only (default option)
  • “w” for write only (erases the content, if the file is not empty)
  • “a” for appending content at the end of the file
  • “r+” for read and write

The “read()” function will read the entire file or the size given as argument.

fileContent = myFile.read()

The “readline()” function will read until it finds a “\n”, and will return an empty string (“”) when it reaches the end of the file.

The “write()” function will write the content in parameter to the file.

myFile.write('Some text to write in the file.')

The “close()” function closes an opened file.

myFile.close()

Exceptions and error handling

Syntax error

Like with most other languages, Python will tell you at which line the error starts in the code.

Exceptions

A try/catch block can be used to catch exceptions, it will also catch exceptions that occured in a function called inside it.

The “except” keyword acts as the “catch” and can handle specific exception types as well as the base class “Exception” to catch all exceptions.

To catch multiple exception types at once, a tuple has to be used.

An “else” can be added at the end (after all “except” instructions) to execute code only in the case that no exception was raised by the “try” block.

try:
    # Some code here...
except NameError:
    print('Name error exception.')
except (RuntimeError, TypeError):
    print('Runtime or Type error exception')
except Exception:
    print('There was an exception.')
else:
    print('Everything went fine!')

Exceptions can be raised with the “raise” keyword, the exception type must be “Exception” or derived from it.

A call to “raise” without any exception type or argument will re-raise the current exception.

raise Exception('This is an exception!')

try:
    functionThatCanRaiseAnException()
except Exception:
    raise

The “finally” block can be added at the end to execute code no matter if an exception has been raised or not, it is generally used to free resources.

try:
    functionThatCanRaiseAnException()
except Exception:
    raise
finally:
    print("This is the finally block.")

Custom exception classes can be made, but they have to derive from “Exception”.

Classes

General information

Python classes support the standard features of object-oriented programming.

Here are some of the things a class can do:

  • Multiple inheritance
  • Method overriding (of any method)
  • Calling to a method of the same name in the base class
  • Can contain any kind and amount of data
  • Can be modified after creation
  • Normal members are public
  • Classes are objects, which means that they can be imported and renamed
  • It is possible to use the built-in types as base classes
  • It is possible to redefine built-in operators in class instances
  • Aliasing (using multiple names for the same object) is allowed

Attributes can be referenced with the dot notation.

myObject.someMethod()

Classes can be instanciated by simply calling their constructor and assigning the return value to a variable, this will create an empty object. To initialize an object on instanciation, we have to define an “__init__()” method inside the object.

The implicit parameter (the actual object calling its own method, defined by “this” in some other languages), must be defined by “self” and written as the first parameter of each method of a class.

class myClass:
    def __init__(self):
        print('Initializing the object.')
    def someMethod(self, text):
        print('You just called the someMethod method with this text: ' + text + '.')

myInstance = myClass()
myInstance.someMethod("Some text")

# Will output (without quotes): "You just called the someMethod method with this text: Some text."

Class variables do not need to be declared, assigning a value to a name of your choice will create it.

myInstance.newVariable = 10
print(myInstance.newVariable)

# Will output (without quotes): "10"

Instance variables have to be declared in the “__init__()” method. When referring to instance variables and methods inside the class, they have to be prefixed with “self.”.

class myClass:
    def __init__(self):
        self.myVariable = 0
        self.myList = []

    def addItem(self, item):
        self.myList.append(item)

A list of the methods and attributes of an object can be obtained with the “dir()” function.

dir(myObject)

Inheritance

To inherit from another class, the name of the base class has to be put between parentheses after the name of the derived class. Methods of the base class can also be overriden if needed.

class myDerivedClass(myBaseClass):

Methods of the base class can be called by refering to the base class. The “self” parameter has to be passed explicitely.

myBaseClass.myMethod(self)

It is possible to know if a class inherits from a particular base class with the “isinstance()” function, it also works with built-in types.

isinstance(myObject, myBaseClass)

Standard library

This section is a list of useful modules that come with a Python installation.

os module

It allows to access the operating system’s interface. This makes possible the management of files, directories and other filesystem actions, as well as running custom commands with the “system()” function.

import os

os.system('echo This is a custom message.')

sys module

It allows, among others, to access to the command line arguments and to redirect “stdin”, “stdout” and “stderr”.

import sys

print('Command line arguments: ' + str(sys.argv))

re module

It allows the use of regular expressions.

math module

The math module allows to use C functions that manage floating point numbers.

random module

As the name says, it helps using random values.

statistics module

Includes functions to calculate statistical values like median, variance, etc.

urllib module

Allows to get and send data to/from the internet.

Mail handling

The “email”, “poplib” and “smtplib” modules allow for processing internet mail data.

datetime module

Obviously, it allows to use dates and time.

Data compression

Each format is accessible through its own module.

Performance measurement

The “timeit”, “profile” and “pstats” modules can be used to measure the performance of code segments and/or instructions.

Quality control

The “doctest” module can be used to write tests directly in the docstring.

The “unittest” module can be used to do standard unit tests using separate files.

Structured data

The “json”, “xml”, “sqlite3” and “csv” modules can be used to handle their respective data.

Other modules

  • The “locale” module allows to format data to specific localizations.
  • Multi-threading is done with the “threading” module.
  • The “logging” module offers the tools for logging.
  • The “decimal” module adds the decimal data type which allows to calculate decimal values using the exact decimal representation (instead of the standard binary representation).
  • The “fractions” module can be used to handle calculations using the decimal data type.
  • The “copy” module allows for copying objects with its “copy()” and “deepcopy()” functions.