What is Python?

Python is a very simple language and has a very straightforward syntax. It encourages programmers to program without prepared code. The simplest directive in Python is the “print” directive — it simply prints out a line.

There are two major Python versions, Python 2 and Python 3. Python 2 and 3 are quite different. This tutorial uses Python 3 because it more semantically correct and supports newer features.



Python uses indentation for blocks, instead of curly braces. Both tabs and spaces are supported, but the standard indentation requires standard Python code to use four spaces

Variables and Types

  • Python is completely object-oriented, and not “statically typed”.
  • No need to declare variables before using them or declare their type.
  • Every variable in Python is an object.


Python supports two types and they are:

  1. Integer
  2. Floating


Strings can be defined either in a double quote or a single quote.

There are additional variations on defining strings that make it easier to include things such as carriage returns, backslashes and Unicode characters. https://docs.python.org/3/tutorial/introduction.html#strings

Operator assignment

Assignments can be done on more than one variable “simultaneously” on the same line like this:


Lists are very similar to arrays. They can contain any type of variable, and they can contain as many variables as you wish. Lists can also be iterated over in a very simple manner. Here is an example of how to build a list.

Basic operators


using operators with a string

using operators with Lists

String Formatting

Python uses C-style string formatting to create new, formatted strings. The “%” operator is used to format a set of variables enclosed in a “tuple” (a fixed-size list), together with a format string, which contains normal text together with “argument specifiers”, special symbols like “%s” and “%d”.

The list can be also be represented using %s, basically, an object which is not a string can be formatted using the %s operator as well.

Important formatters to be remembered

  • %s — String (or any object with a string representation, like numbers)
  • %d — Integers
  • %f — Floating point numbers
  • %.f — Floating point numbers with a fixed amount of digits to the right of the dot.
  • %x / %X — Integers in hex representation (lowercase/uppercase)

Basic String Operations

Strings are bits of text. They can be defined as anything between quotes

The multiple methods(iun-built) for string are:

  • len()
  • index()
  • count()
  • upper()
  • lower()
  • startswith()
  • endswith()
  • split()

Special list operations


Python uses boolean variables to evaluate conditions. The boolean values True and False are returned when an expression is compared or evaluated.

Boolean operators

The “and” and “or” boolean operators allow building complex boolean expressions.

The “in” operator

The “in” operator could be used to check if a specified object exists within an iterable object container, such as a list:

  • Python uses indentation to define code blocks, instead of brackets.
  • The standard Python indentation is 4 spaces, although tabs and any other space size will work, as long as it is consistent.
  • Notice that code blocks do not need any termination.


A statement is evaluated as true if one of the following is correct:

  1. The “True” boolean variable is given or calculated using an expression, such as an arithmetic comparison.
  2. An object which is not considered “empty” is passed.

The ‘is’ operator

Unlike the double equals operator “==”, the “is” operator does not match the values of the variables, but the instances themselves.

The “not” operator

Using “not” before a boolean expression inverts it:


There are two types of loops in Python, for and while.

The “for” loop

range() vs xrange()

  • range() and xrange() are two functions that could be used to iterate a certain number of times in for loops in Python.
  • Note: In Python 3, there is no xrange, but the range function behaves like xrange in Python 2.
  • Note: If you want to write code that will run on both Python 2 and Python 3, you should use range().


This returns a list of numbers created using the range() function.


This function returns the generator object that can be used to display numbers only by looping. The only particular range is displayed on demand and hence called “lazy evaluation“.

Both are implemented in different ways and have different characteristics associated with them. The points of comparisons are:

  • Return Type
  • Memory
  • Operation Usage
  • Speed

Return Type

  • range() returns — the list as return type.
  • xrange() returns — xrange() object.


“while” loops

While loops repeat as long as a certain boolean condition is met.

“break” and “continue” statements


is used to exit a for loop or a while loop


is used to skip the current block


can we use the “else” clause for loops?

unlike languages like C, CPP.. we can use else for loops. When the loop condition of the “for” or “while” statement fails then the code part in “else” is executed. If the break statement is executed inside for loop then the “else” part is skipped. Note that the “else” part is executed even if there is a continue statement.



What are Functions?

Functions are a convenient way to divide your code into useful blocks, allowing us to order our code, make it more readable, reuse it and save some time. Also, functions are a key way to define interfaces so programmers can share their code.

How do you write functions in Python?

Python makes use of blocks.

Where a block line is more Python code (even another block), and the blockhead is of the following format: block_keyword block_name(argument1,argument2, …) Block keywords you already know are “if”, “for”, and “while”.

Functions in Python are defined using the block keyword “def”, followed by the function’s name as the block’s name.

Import feature

Classes and Objects

  • Objects are an encapsulation of variables and functions into a single entity.
  • Objects get their variables and functions from classes. Classes are essentially a template to create your objects.

A very basic example is that:

Now the variable “myobjectx” holds an object of the class “MyClass” that contains the variable and the function defined within the class called “MyClass”.

Accessing Object Variables

You can create multiple different objects that are of the same class(have the same variables and functions defined). However, each object contains independent copies of the variables defined in the class.


A dictionary is a data type similar to arrays but works with keys and values instead of indexes. Each value stored in a dictionary can be accessed using a key, which is any type of object (a string, a number, a list, etc.) instead of using its index to address it.

Alternatively, a dictionary can be initialized with the same values in the following notation:

Iterating over dictionaries

Dictionaries can be iterated over, just like a list. However, a dictionary, unlike a list, does not keep the order of the values stored in it. To iterate over key-value pairs, use the following syntax:

Removing a value

To remove a specified index, use either one of the following notations:

Modules and Packages

In programming, a module is a piece of software that has a specific functionality. For example, when building a ping pong game, one module would be responsible for the game logic, and another module would be responsible for drawing the game on the screen. Each module is a different file, which can be edited separately.

Exploring built-in modules

Check out the complete list of built-in modules in the python standard library.

Two very important functions come in handy when exploring modules in Python:

  • dir
  • help

We can look for which functions are implemented in each module by using the dir function:

Numpy Arrays

Numpy arrays are great alternatives to Python Lists. Some of the key advantages of Numpy arrays are that they are fast, easy to work with and allow users to perform calculations across entire arrays.


Pandas Basics

Pandas DataFrames

  • Pandas is a high-level data manipulation tool developed by Wes McKinney.

There are several ways to create a DataFrame. One way is to use a dictionary. For example:

As you can see with the new BRICS DataFrame, Pandas has assigned a key for each country as the numerical values 0 through 4. If you would like to have different index values, say, the two-letter country code, you can do that easily as well.


Generators are very easy to implement, but a bit difficult to understand.

Generators are used to create iterators, but with a different approach. Generators are simple functions that return an iterable set of items, one at a time, in a special way.

When an iteration over a set of the item starts using the for statement, the generator is run. Once the generator’s function code reaches a “yield” statement, the generator yields its execution back to the for loop, returning a new value from the set. The generator function can generate as many values (possibly infinite) as it wants, yielding each one in its turn.


List Comprehensions

List Comprehensions is a very powerful tool, which creates a new list based on another list, in a single, readable line.

For example, let’s say we need to create a list of integers that specify the length of each word in a certain sentence, but only if the word is not the word “the”.

Before list comprehension:

After list comprehension:

Multiple Function Arguments

Every function in Python receives a predefined number of arguments.

It is possible to declare functions that receive a variable number of arguments, using the following syntax:

It is also possible to send functions arguments by keyword so that the order of the argument does not matter, using the following syntax.

Regular Expressions

Regular Expressions (sometimes shortened to regexp, regex, or re) are a tool for matching patterns in text. In Python, we have the re module. The applications for regular expressions are widespread, but they are fairly complex, so when contemplating using a regex for a certain task, think about alternatives, and come to regexes as a last resort.

An example regex is r”^(From|To|Cc).*?python-list@python.org” Now for an explanation: the caret ^ matches text at the beginning of a line. The following group, the part with (From|To|Cc) means that the line has to start with one of the words that are separated by the pipe |. That is called the OR operator, and the regex will match if the line starts with any of the words in the group. The .*? means to un-greedily match any number of characters, except the newline \n character. The un-greedy part means to match as few repetitions as possible. The ‘.‘ character means any non-newline character, the * means to repeat 0 or more times, and the? character makes it un-greedy.

So, the following lines would be matched by that regex: From python-list@python.org To: !asp]<,. python-list@python.org

Click for a complete reference of the re syntax

As an example of a “proper” email-matching regex, click here

Exception Handling

When programming, errors happen. It’s just a fact of life. Perhaps the user gave bad input. Maybe a network resource was unavailable. Maybe the program ran out of memory. Or the programmer may have even made a mistake!

But sometimes you don’t want exceptions to completely stop the program. You might want to do something special when an exception is raised. This is done in a try/except block.



Sets are lists with no duplicate entries. Let’s say you want to collect a list of words used in a paragraph:

The different methods are:

  • intersection()
  • symmetric_difference()
  • difference()
  • union()


Data serialization is the concept of converting structured data into a format that allows it to be shared or stored in such a way that its original structure to be recovered. In some cases, the secondary intention of data serialization is to minimize the size of the serialized data which then minimizes disk space or bandwidth requirements.


The native data serialization module for Python is called Pickle.


Partial functions

You can create partial functions in python by using the partial function from the function tools library.

Partial functions allow one to derive a function with x parameters to a function with fewer parameters and fixed values set for the more limited function.


Note: An important note: the default values will start replacing variables from the left. The 2 will replace x. y will equal 4 when dbl(4) is called. It does not make a difference in this example, but it does in the example above.

Code Introspection

Code introspection is the ability to examine classes, functions and keywords to know what they are, what they do and what they know.

Python provides several functions and utilities for code introspection.

  • help()
  • dir()
  • hasattr()
  • id()
  • type()
  • repr()
  • callable()
  • issubclass()
  • isinstance()
  • __doc__
  • __name__

Note: Often the most important one is the help function since you can use it to find what other functions do.



Firstly, a Nested Function is a function defined inside another function. It’s very important to note that the nested functions can access the variables of the enclosing scope. However, at least in python, they are only read-only. However, one can use the “nonlocal” keyword explicitly with these variables to modify them.

Before using nonlocal

After using nonlocal

Without the nonlocal keyword, the output would be “3 9”, however, with its usage, we get “3 3”, that is the value of the “number” variable gets modified.

ADVANTAGE: Closures can avoid the use of global variables and provides some form of data hiding. (Eg. When there are few methods in a class, use closures instead).


  • Classes can inherit from other classes.
  • A class can inherit attributes and behaviour methods from another class, called the superclass.
  • A class that inherits from a superclass is called a subclass, also called heir class or child class.
  • Superclasses are sometimes called ancestors as well. There exists a hierarchical relationship between classes. It’s similar to relationships or categorizations that we know from real life.

The __init__ method of our Employee class explicitly invokes the __init__method of the Person class. We could have used super instead. super().__init__(first, last) is automatically replaced by a call to the superclasses method, in this case, __init__:


Please note that we used super()) without arguments. This is only possible in Python3. We could have written “super(Employee, self).__init__(first, last, age)” which still works in Python3 and is compatible with Python2.

To be continued……………………

I am Master's student in the Netherlands and has a previous work experience of 4 years in the field of Software Development.