Category: beginner
Introduction
Welcome to my Python Course!
Python is a general-purpose computer programming language.
This course is suitable for both Python 2 and Python 3.
Related Course:
Python Programming Bootcamp: Go from zero to hero
Download Python
To run Python code, you will need one of these programs:
For terminal only: Apple Mac OS X, Microsoft Windows, Linux/UNIX
<caption id=”attachment_3478” align=”alignnone” width=”300”]
Run Python code
A python program should be save as a file with a .py extension.
Try this code:
print("Hello World!") |
Expected output:
Hello World! |
If you are using the interpreter use:
python program.py |
python if string equals

A string is a series of characters, they are mostly used to display text.
To define a string simply type text between quotes. Python accepts single, double and triple quotes.
Related Course:
Python Programming Bootcamp: Go from zero to hero
String input and output
To output text (string) to the screen:
s = "hello world" |
To get text from keyboard:
|
If you use an old Python version (2.x), you need to use:
|
To test your version:
python –version
String Comparison
To test if two strings are equal use the equality operator (==).
#!/usr/bin/python |
To test if two strings are not equal use the inequality operator (!=)
#!/usr/bin/python |
If you are new to Python programming, I highly recommend this book.
python string slice
A string is a series of characters, they are mostly used to display text.
To define a string simply type text between quotes. Python accepts single, double and triple quotes.
Related Course:
Python Programming Bootcamp: Go from zero to hero
String Index
Python indexes the characters of a string, every index is associated with a unique character. For instance, the characters in the string ‘python’ have indices:

Characters in string
The 0th index is used for the first character of a string. Try the following:
#!/usr/bin/python |
String Slicing
Given a string s, the syntax for a slice is:
s[ startIndex : pastIndex ] |
The startIndex is the start index of the string. pastIndex is one past the end of the slice.
If you omit the first index, the slice will start from the beginning. If you omit the last index, the slice will go to the end of the string. For instance:
#!/usr/bin/python |
variables in python

Variables can hold numbers that you can use one or more times.
Numbers can be of one of these datatypes:
- integer (1,2,3,4)
- float (numbers behind the dot)
- boolean (True or False)
Related Course:
Python Programming Bootcamp: Go from zero to hero
Numeric variables example
Example of numeric variables:
x = 1 |
You can output them to the screen using the print() function.
x = 1 |
Python supports arithmetic operations like addition (+), multiplication (*), division (/) and subtractions (-).
#!/usr/bin/env python |
User input
Python 3
Use the input() function to get text input, convert to a number using int() or float().
#!/usr/bin/env python |
Python 2 (old version)
You can also ask the user for input using the raw_input function:
#!/usr/bin/env python |
If you are new to Python programming, I highly recommend this book.
python lists, lists in python, python
Lists is a sequence and a basic data structure. A list may contain strings (text) and numbers. A list is similar to an array in other programming languages, but has additional functionality.
Related Course:
Python Programming Bootcamp: Go from zero to hero
Python List
We define lists with brackets []. To access the data, these same brackets are used.
Example list usage:
#!/usr/bin/python |
Add/remove
We can use the functions append() and remove() to manipulate the list.
#!/usr/bin/python |
Sort list
We can sort the list using the sort() function.
#!/usr/bin/python |
If you want to have the list in descending order, simply use the reverse() function.
#!/usr/bin/python |
If you are new to Python programming, I highly recommend this book.
if statement python
In Python you can define conditional statements, known as if-statements.
A block of code is executed if certain conditions are met.
Related Course:
Python Programming Bootcamp: Go from zero to hero
If statements
Consider this application, it executes either the first or second code depending on the value of x.
|
If you set x to be larger than 10, it will execute the second code block. We use indentation (4 spaces) to define the blocks.
A little game:
A variable may not always be defined by the user, consider this little game:
age = 24 |
Conditional operators
A word on conditional operators
Operator | Description |
!= | not equal |
== | equals |
> | greater than |
< | smaller than |
a = 12 |
This can quickly become difficult to read, consider combining 4 or 6 conditions. Luckily Python has a solution for this, we can combine conditions using the and keyword.
guess = 24 |
Sometimes you may want to use the or operator.
If you are new to Python programming, I highly recommend this book.
python function
A function is reusable code that can be called anywhere in your program. Functions improve readability of your code: it’s easier for someone to understand code using functions instead of long lists of instructions.
On top of that, functions can be reused or modified which also improve testability and extensibility.
Related Course:
Python Programming Bootcamp: Go from zero to hero
Function definition
We use this syntax to define as function:
def function(parameters): |
The def keyword tells Python we have a piece of reusable code (A function). A program can have many functions.
Practical Example
We can call the function using function(parameters).
#!/usr/bin/python |
Output:
9 |
The function has one parameter, x. The return value is the value the function returns. Not all functions have to return something.
Parameters
We can pass multiple variables:
#!/usr/bin/python |
Output:
|
If you are new to Python programming, I highly recommend this book.
python global variable
There are two types of variables: global variables and local variables.
A global variable can be reached anywhere in the code, a local only in the scope.

Related Course:
Python Programming Bootcamp: Go from zero to hero
Local variables
Local variables can only be reached in their scope.
The example below has two local variables: x and y.
|
The variables x and y can only be used inside the function sum, they don’t exist outside of the function.
Local variables cannot be used outside of their scope, this line will not work:
|
Global variables
A global variable can be used anywhere in the code.
In the example below we define a global variable z
|
The global variable z can be used all throughout the program, inside functions or outside.
A global variable can modified inside a function and change for the entire program:
|
After calling afunction(), the global variable is changed for the entire program.
Exercise
Local and global variables can be used together in the same program.
Try to determine the output of this program:
|
If you are new to Python programming, I highly recommend this book.
what is scope in python
Scope
Variables can only reach the area in which they are defined, which is called scope. Think of it as the area of code where variables can be used. Python supports global variables (usable in the entire program) and local variables.
By default, all variables declared in a function are local variables. To access a global variable inside a function, it’s required to explicitly define ‘global variable’.
Related Course:
Python Programming Bootcamp: Go from zero to hero
Example
Below we’ll examine the use of local variables and scope. This will not work:
#!/usr/bin/python |
but this will:
#!/usr/bin/python |
Let’s examine this further:
#!/usr/bin/python |
Calling functions in functions
We can also get the contents of a variable from another function:
#!/usr/bin/python |
If a variable can be reached anywhere in the code is called a global variable. If a variable is known only inside the scope, we call it a local variable.
If you are new to Python programming, I highly recommend this book.
python for loop
Code can be repeated using a loop. Lines of code can be repeated N times, where N is manually configurable. In practice, it means code will be repeated until a condition is met. This condition is usually (x >=N) but it’s not the only possible condition.
Python has 3 types of loops: for loops, while loops and nested loops.
Related Course:
Python Programming Bootcamp: Go from zero to hero
For loop
We can iterate a list using a for loop#!/usr/bin/python |
Visualization of for loop:
The for loop can be used to repeat N times too:
#!/usr/bin/python |
While loop
If you are unsure how many times a code should be repeated, use a while loop.
For example,
|
Nested loops
We can combine for loops using nesting. If we want to iterate over an (x,y) field we could use:
#!/usr/bin/python |
Nesting is very useful, but it increases complexity the deeper you nest.
If you are new to Python programming, I highly recommend this book.
python range
The range() function returns of generates a sequence of numbers, starting from the lower bound to the upper bound.
|
- lower_bound: The starting value of the list.
- upper_bound: The max value of the list, excluding this number.
- step_bound: The step size, the difference between each number in the list.
The lower_bound and step_size parameters are optional. By default the lower bound is set to zero, the incremental step is set to one. The parameters must be of the type integers, but may be negative.

Related Course:
Python Programming Bootcamp: Go from zero to hero
range implementation difference
This distinction won’t usually be an issue. The range() is implemented slightly different in the Python versions:
- Python 2.x: The range() function returns a list.
- Python 3.x: The range() function generates a sequence.
range in python 2.7
A call to range(5) will return: 0,1,2,3,4.
|
A call to range(1,10) returns: 1,2,3,4,5,6,7,8,9
|
Calling range(0,10,2) returns: 0,2,4,6,8
|
range in python 3
To generate a list using range, add the list function
|
We can use all parameters (lower bound, upper bound, step)
|
python 2 implementation
This version of range() allocates computer memory and also populates the computer memory behind the scenes. For large ranges, this is implementation is not very efficient.
Usually you won’t have any issues with the Python2 implementation of range() but if you use large numbers (millions of items) you could run into issues.
If you are new to Python programming, I highly recommend this book.
python tuple
The tuple data structure is used to store a group of data. The elements in this group are separated by a comma. Once created, the values of a tuple cannot change.
Related Course:
Python Programming Bootcamp: Go from zero to hero
Python Tuple
An empty tuple in Python would be defined as:
tuple = () |
A comma is required for a tuple with one item:
tuple = (3,) |
The comma for one item may be counter intuitive, but without the comma for a single item, you cannot access the element. For multiple items, you do not have to put a comma at the end. This set is an example:
personInfo = ("Diana", 32, "New York") |
The data inside a tuple can be of one or more data types such as text and numbers.
Data access
To access the data we can simply use an index. As usual, an index is a number between brackets:
#!/usr/bin/env python |
If you want to assign multiple variables at once, you can use tuples:
#!/usr/bin/env python |
On the right side the tuple is written. Left of the operator equality operator are the corresponding output variables.
Append to a tuple in Python
If you have an existing tuple, you can append to it with the + operator. You can only append a tuple to an existing tuple.
#!/usr/bin/env python |
If you are new to Python programming, I highly recommend this book.
python dictionary
A dictionary can be thought of as an unordered set of key: value pairs.
A pair of braces creates an empty dictionary: {}. Each element can maps to a certain value. An integer or string can be used for the index. Dictonaries do not have an order.
Related Course:
Python Programming Bootcamp: Go from zero to hero
Dictionary example
Let us make a simple dictionary:
#!/usr/bin/python |
Output:
|
We are by no means limited to single word defintions in the value part. A demonstration:
#!/usr/bin/python |
Output:
|
Manipulating the dictionary
We can manipulate the data stored in a dictionairy after declaration. This is shown in the example below:
#!/usr/bin/python |
Output:
|
If you are new to Python programming, I highly recommend this book.
python cast
Python determines the datatype automatically, to illustrate:
|
It finds x is of type integer and y of type string.
Functions accept a certain datatype. For example, print only accepts the string datatype.
Related Course:
Python Programming Bootcamp: Go from zero to hero
Datatypes casting
If you want to print numbers you will often need casting.
In this example below we want to print two numbers, one whole number (integer) and one floating point number.
x = 3 |
We cast the variable x (integer) and the variable y (float) to a string using the str() function.
What if we have text that we want to store as number? We will have to cast again.
a = "135.31421" |
In the example above we cast two variables with the datatype string to the datatype float.
Conversion functions
To convert between datatypes you can use:
Function | Description |
---|---|
int(x) | Converts x to an integer |
long(x) | Converts x to a long integer |
float(x) | Converts x to a floating point number |
str(x) | Converts x to an string. x can be of the type float. integer or long. |
hex(x) | Converts x integer to a hexadecimal string |
chr(x) | Converts x integer to a character |
ord(x) | Converts character x to an integer |
from random import * |
Generate a random number between 1 and 100
To generate a whole number (integer) between one and one hundred use:
from random import * |
This will printa random integer. If you want to store it in a variable you can use:
from random import * |
Random number between 1 and 10
To generate a random floating point number between 1 and 10 you can use the uniform() function
from random import * |
Picking a random item from a list
Fun with lists
We can shuffle a list with this code:
from random import * |
To pick a random number from a list:
from random import * |
We can do the same thing with a list of strings:
from random import * |
If you are new to Python programming, I highly recommend this book.
How to Read a File in Python
You have seen various types of data holders before: integers, strings, lists. But so far, we have not discussed how to read or write files.
Related Course:
Python Programming Bootcamp: Go from zero to hero
Read file
The Python programming language provides the ability to work with files using open()
.
Python programming treats some files as text files, where lines are separated by newline characters \n
. You can open regular files with the paramater r
.
Other files are considered binary and can be handled in a way that is similar to the C programming language. They need to be opened with the parameters rb
.
read file into string
This is a sample program that shows how to read data from a file.
The file needs to be in the same directory as the program, if not you need to specify a path.
Create python script. Open editor of your choice and create new python script. Then paste the following code.
f = open("file.txt","r") |
The read method readlines()
reads all the contents of a file into a string.
Save the file with name example.py and run it.
read file line by line
To output line by line, you can use a for loop. The lines may include a new line character \n
, that is why you can output using endl=""
.
f = open("filename.txt","r") |
Another option is to remove the newline characters with the replace() method.
f = open("test.py","r") |
read file with keyword
The with keyword can be used to read files too. This automatically closes your file.
#!/usr/bin/env python |
The first part of the code will read the file content. All of the lines read will be stored in the variable content. The second part will iterate over every line in the variable contents.
If you do not want to read the newline characters ‘\n’, you can change the statement f.readlines() to this:
content = f.read().splitlines() |
Resulting in this code:
#!/usr/bin/env python |
While the codes above work, we should always test if the file we want to open exists. We will test first if the file does not exist, if it does it will read the file else return an error. As in the code below:
#!/usr/bin/env python |
If you are new to Python programming, I highly recommend this book.
python write to file
Python supports writing files by default, no special modules are required. You can write a file using the .write() method with a parameter containing text data.
Before writing data to a file, call the open(filename,’w’) function where filename contains either the filename or the path to the filename. Finally, don’t forget to close the file.
Related Course:
Python Programming Bootcamp: Go from zero to hero
Create file for writing
The code below creates a new file (or overwrites) with the data.
#!/usr/bin/env python |
The ‘w’ flag makes Python truncate the file if it already exists. That is to say, if the file contents exists it will be replaced.
Append to file
If you simply want to add content to the file you can use the ‘a’ parameter.
#!/usr/bin/env python |
Parameters
A summary of parameters:
Flag | Action |
---|---|
r | Open file for reading |
w | Open file for writing (will truncate file) |
b | binary more |
r+ | open file for reading and writing |
a+ | open file for reading and writing (appends to end) |
w+ | open file for reading and writing (truncates files) |
class User: |
Run this program. In this code we have 3 virtual objects: james, david and eric. Each object is instance of the User class.

In this class we defined the sayHello() method, which is why we can call it for each of the objects. The init() method is called the constructor and is always called when creating an object. The variables owned by the class is in this case “name”. These variables are sometimes called class attributes.
We can create methods in classes which update the internal variables of the object. This may sound vague but I will demonstrate with an example.
Class variables
We define a class CoffeeMachine of which the virtual objects hold the amount of beans and amount of water. Both are defined as a number (integer). We may then define methods that add or remove beans.
def addBean(self): |
We do the same for the variable water. As shown below:
class CoffeeMachine: |
Run this program. The top of the code defines the class as we described. The code below is where we create virtual objects. In this example we have exactly one object called “pythonBean”. We then call methods which change the internal variables, this is possible because we defined those methods inside the class. Output:
|
If you are new to Python programming, I highly recommend this book.
python class tutorial
Everything in Python is an object. Every object can contain methods and variables (with unique values). Objects are created (often called instantiated) from classes.
Related courses
Python Programming Bootcamp: Go from zero to hero
Class example
Consider the example below:
|
We create one object called ‘duck’ from the class Animal. The class has a method (walk) that can be called on each object. We also have a method called init(), this is a method that is always called when a new object is created. The self keyword is required for every method. We set the variables with the class (self.name = ..).

Once the object is created, we can call its methods and use its variables indefinitely. Every object of the same class has the same methods, but its variables contents may differ.
A Python program may consists of many classes and objects. To demonstrate that, we create two objects from one class:
|
If you are new to Python programming, I highly recommend this book.
encapsulation in python
In an object oriented python program, you can restrict access to methods and variables. This can prevent the data from being modified by accident and is known as encapsulation. Let’s start with an example.
Related Courses:
Python Programming Bootcamp: Go from zero to hero
Private methods

We create a class Car which has two methods: drive() and updateSoftware(). When a car object is created, it will call the private methods __updateSoftware().
This function cannot be called on the object directly, only from within the class.
#!/usr/bin/env python |
This program will output:
updating software |
Encapsulation prevents from accessing accidentally, but not intentionally.
The private attributes and methods are not really hidden, they’re renamed adding _Car” in the beginning of their name.
The method can actually be called using redcar._Car__updateSoftware()
Private variables

Variables can be private which can be useful on many occasions. A private variable can only be changed within a class method and not outside of the class.
Objects can hold crucial data for your application and you do not want that data to be changeable from anywhere in the code.
An example:
#!/usr/bin/env python |
If you want to change the value of a private variable, a setter method is used. This is simply a method that sets the value of a private variable.
#!/usr/bin/env python |
Why would you create them? Because some of the private values you may want to change after creation of the object while others may not need to be changed at all.
Python Encapsulation
To summarize, in Python there are:
Type | Description |
---|---|
public methods | Accessible from anywhere |
private methods | Accessible only in their own class. starts with two underscores |
public variables | Accessible from anywhere |
private variables | Accesible only in their own class or by a method if defined. starts with two underscores |
#!/usr/bin/env python |
Output:
Hello |
To clarify method overloading, we can now call the method sayHello() in two ways:
obj.sayHello() |
We created a method that can be called with fewer arguments than it is defined to allow.
We are not limited to two variables, your method could have more variables which are optional.
If you are new to Python programming, I highly recommend this book.
python class inheritance
Classes can inherit functionality of other classes. If an object is created using a class that inherits from a superclass, the object will contain the methods of both the class and the superclass. The same holds true for variables of both the superclass and the class that inherits from the super class.
Python supports inheritance from multiple classes, unlike other popular programming languages.
Related Course:
Python Programming Bootcamp: Go from zero to hero
Intoduction
We define a basic class named User:
class User: |
This creates one instance called brian which outputs its given name. We create another class called Programmer.
class Programmer(User): |
This looks very much like a standard class except than User is given in the parameters. This means all functionality of the class User is accessible in the Programmer class.
Inheritance example
Full example of Python inheritance:
class User: |
The output:
Name = brian |
Brian is an instance of User and can only access the method printName. Diana is an instance of Programmer, a class with inheritance from User, and can access both the methods in Programmer and User.
If you are new to Python programming, I highly recommend this book.
Polymorphism
Sometimes an object comes in many types or forms. If we have a button, there are many different draw outputs (round button, check button, square button, button with image) but they do share the same logic: onClick(). We access them using the same method . This idea is called Polymorphism.
Polymorphism is based on the greek words Poly (many) and morphism (forms). We will create a structure that can take or use many forms of objects.
Related Course:
Python Programming Bootcamp: Go from zero to hero
Polymorphism with a function:
We create two classes: Bear and Dog, both can make a distinct sound. We then make two instances and call their action using the same method.
class Bear(object): |
Output:
Groarrr |
Polymorphism with abstract class (most commonly used)

Abstract structure is defined in Document class.
If you create an editor you may not know in advance what type of documents a user will open (pdf format or word format?).
Wouldn’t it be great to acess them like this, instead of having 20 types for every document?
for document in documents: |
To do so, we create an abstract class called document. This class does not have any implementation but defines the structure (in form of functions) that all forms must have. If we define the function show() then both the PdfDocument and WordDocument must have the show() function. Full code:
class Document: |
Output:
Document1: Show pdf contents! |
We have an abstract access point (document) to many types of objects (pdf,word) that follow the same structure.
Related Course:
Python Programming Bootcamp: Go from zero to hero
Polymorphism example

Another example would be to have an abstract class Car which holds the structure drive() and stop().
We define two objects Sportscar and Truck, both are a form of Car. In pseudo code what we will do is:
class Car: |
Then we can access any type of car and call the functionality without taking further into account if the form is Sportscar or Truck. Full code:
class Car: |
Output:
Bananatruck: Truck driving slowly because heavily loaded. |
If you are new to Python programming, I highly recommend this book.
python inner class
An inner class or nested class is a defined entirely within the body of another class. If an object is created using a class, the object inside the root class can be used. A class can have more than one inner classes, but in general inner classes are avoided.
One of the most useful and powerful features of Python is its ability to nest classes within classes. A nested class is a class defined within another class, and inherits all the variables and methods of the parent class.
Related Course:
Python Programming Bootcamp: Go from zero to hero
Inner class example
Python has inner classes. Inner classes are classes that are defined inside other classes. Inner classes have access to all the members of their outer classes.
Indention is very important when using inner classes. Every inner class should be indented by 4 spaces.
We create a class (Human) with one inner class (Head). An instance is created that calls a method in the inner class:
#!/usr/bin/env python |
Output:
Guido |
In the program above we have the inner class Head() which has its own method. An inner class can have both methods and variables. In this example the constructor of the class Human (init) creates a new head object.
Multiple inner classes
You are by no means limited to the number of inner classes, for example this code will work too:
#!/usr/bin/env python |
By using inner classes you can make your code even more object orientated. A single object can hold several sub objects. We can use them to add more structure to our programs.
Why inner class?
An inner class lets you group classes. They have some advantages over using only distinct classes.
- Inner class has a local scope
- Easy to understand which classes are related
Inner classes (sometimes callled nested classes) are not widely used in Python.
If you are new to Python programming, I highly recommend this book.
python factory
We may not always know what kind of objects we want to create in advance.
Some objects can be created only at execution time after a user requests so.
Examples when you may use a factory method:
- A user may click on a certain button that creates an object.
- A user may create several new documents of different types.
- If a user starts a webbrowser, the browser does not know in advance how many tabs (where every tab is an object) will be opened.
Related Course:
Python Programming Bootcamp: Go from zero to hero
Factory method pattern
To deal with this we can use the factory method pattern.
The idea is to have one function, the factory, that takes an input string and outputs an object.
obj = Car.factory("Racecar") |
Key fact: a factory method returns (new) objects.
The type of object depends on the type of input string you specify. This technique could make your program more easily extensible also. A new programmer could easily add functionality by adding a new string and class, without having to read all of the source code.
Factory method example
The example below demonstrates a factory method. The factory method (named factory) returns a new object of either type depending on the input.
|
Output:
Racecar driving. |
If you are new to Python programming, I highly recommend this book.
recursion in python w3schools
In English there are many examples of recursion:
- "To understand recursion, you must first understand recursion",
- "A human is someone whose mother is human".
You might wonder, what does this have to do with programming?
You may want to split a complex problem into several smaller ones. You are already familiar with loops or iterations. In some situations recursion may be a better solution.
In Python, a function is recursive if it calls itself and has a termination condition. Why a termination condition? To stop the function from calling itself ad infinity.
Related Course:
Python Programming Bootcamp: Go from zero to hero
Recursion examples
Recursion in with a list
Let’s start with a very basic example: adding all numbers in a list. Without recursion, this could be:
#!/usr/bin/env python |
Where we simply call the sum function, the function adds every element to the variable sum and returns. To do this recursively:
#!/usr/bin/env python |
If the length of the list is one it returns the list (the termination condition). Else, it returns the element and a call to the function sum() minus one element of the list. If all calls are executed, it returns reaches the termination condition and returns the answer.
Factorial with recursion
The mathematical definition of factorial is: n! = n * (n-1)!, if n > 1 and f(1) = 1. Example: 3! = 3 x 2 x 1 = 6. We can implement this in Python using a recursive function:
#!/usr/bin/env python |
When calling the factorial function n = 3. Thus it returns n * factorial(n-1). This process will continue until n = 1. If n==1 is reached, it will return the result.
Limitations of recursions
Everytime a function calls itself and stores some memory. Thus, a recursive function could hold much more memory than a traditional function. Python stops the function calls after a depth of 1000 calls. If you run this example:
#!/usr/bin/env python |
You will get the error:
RuntimeError: maximum recursion depth exceeded |
In other programming languages, your program could simply crash. You can resolve this by modifying the number of recursion calls such as:
#!/usr/bin/env python |
but keep in mind there is still a limit to the input for the factorial function. For this reason, you should use recursion wisely. As you learned now for the factorial problem, a recursive function is not the best solution. For other problems such as traversing a directory, recursion may be a good solution.
Related Course:
Python Programming Bootcamp: Go from zero to hero
python logging
Python logging
We can track events in a software application, this is known as logging. Let’s start with a simple example, we will log a warning message.
As opposed to just printing the errors, logging can be configured to disable output or save to a file. This is a big advantage to simple printing the errors.
Related course
Python Programming Bootcamp: Go from zero to hero
Logging example
import logging |
This will output:
WARNING:root:This is a warning! |
We can easily output to a file:
import logging |
The importance of a log message depends on the severity.
Level of severity
The logger module has several levels of severity. We set the level of severity using this line of code:
logging.basicConfig(level=logging.DEBUG) |
These are the levels of severity:
Type | Description |
---|---|
DEBUG | Information only for problem diagnostics |
INFO | The program is running as expected |
WARNING | Indicate something went wrong |
ERROR | The software will no longer be able to function |
CRITICAL | Very serious error |
import logging |
Time in log
You can enable time for logging using this line of code:
logging.basicConfig(format='%(asctime)s %(message)s') |
An example below:
import logging |
Output:
2015-06-25 23:24:01,153 Logging app started |
Related course
Python Programming Bootcamp: Go from zero to hero
python subprocess
The subprocess module enables you to start new applications from your Python program. How cool is that?
Related Course:
Python Programming Bootcamp: Go from zero to hero
Start a process in Python:
You can start a process in Python using the Popen function call. The program below starts the unix program ‘cat’ and the second parameter is the argument. This is equivalent to ‘cat test.py’. You can start any program with any parameter.
#!/usr/bin/env python |
The process.communicate() call reads input and output from the process. stdout is the process output. stderr will be written only if an error occurs. If you want to wait for the program to finish you can call Popen.wait().
Subprocess call():
Subprocess has a method call() which can be used to start a program. The parameter is a list of which the first argument must be the program name. The full definition is:
subprocess.call(args, *, stdin=None, stdout=None, stderr=None, shell=False) |
In the example below the full command would be “ls -l”
#!/usr/bin/env python |
Save process output (stdout)
We can get the output of a program and store it in a string directly using check_output. The method is defined as:
subprocess.check_output(args, *, stdin=None, stderr=None, shell=False, universal_newlines=False) |
Example usage:
#!/usr/bin/env python |
If you are new to Python programming, I highly recommend this book.
python threading
python lambda if
We can create anonymous functions, known as lambda functions. Lambda functions are different from normal Python functions, they originate from Lambda Calculus. It allows you to write very short functions.
Related Course:Python Programming Bootcamp: Go from zero to hero
Lambda function example
This code shows the use of a lambda function:
#!/usr/bin/env python |
A return statements is never used in a lambda function, it always returns
something. A lambda functions may contain if statements:
#!/usr/bin/env python |
map function
The definition of map is map(function,iterable). It applies a function to every item in the iteratable. We can use map() on a lambda function with a list:
#!/usr/bin/env python |
Anywhere you use lambda functions, you could use normal functions instead. A lambda function is not a statement, it is an expression. Lambda functions do not support a block of statements.
filter function
filter(function,iterable) creates a new list from the elements for which the function returns True. Example:
#!/usr/bin/env python |
The returning list returns contains only the elements for which the lambda expression “lamba x: x % 2 == 0” is true.
reduce function
The reduce function, reduce(function, iterable) applies two arguments cumulatively to the items of iterable, from left to right. Example:
#!/usr/bin/env python |
In this case the expression is always true, thus it simply sums up the elements of the list. Another example:
#!/usr/bin/env python |
Related Course:
Python Programming Bootcamp: Go from zero to hero
python create set
Sets in Python
A set in Python is a collection of objects. Sets are available in Python 2.4 and newer versions. They are different from lists or tuples in that they are modeled after sets in mathematics.
Related course
Python Programming Bootcamp: Go from zero to hero
Set example
To create a set, we use the set() function.
#!/usr/bin/env python |
If we add the same item element multiple times, they are removed. A set may not contain the same element multiple times.
#!/usr/bin/env python |
Simple notation
If you use Python version 2.6 or a later version, you can use a simplified notation:
#!/usr/bin/env python |
Set Methods
Clear elements from set
To remove all elements from sets:
#!/usr/bin/env python |
Add elements to a set
To add elements to a set:
#!/usr/bin/env python |
Remove elements to a set
To remove elements to a set:
!/usr/bin/env python |
Difference between two sets
To find the difference between two sets use:
#!/usr/bin/env python |
Be aware that x.difference(y) is different from y.difference(x).
Subset
To test if a set is a subset use:
#!/usr/bin/env python |
Super-set
To test if a set is a super-set:
#!/usr/bin/env python |
Intersection
To test for intersection, use:
#!/usr/bin/env python |
Related course
Python Programming Bootcamp: Go from zero to hero
python modules tutorial
Modular programming
As you are programming, the software can quickly scale into a large code base. To manage complexity we can use classes, functions and modules.
Related course
Python Programming Bootcamp: Go from zero to hero
Module content
To show the accessible functions (and included variables) in a module, you can use this code:
#!/usr/bin/env python |
Result:
|
Create a Module
You can create your own module in these steps:
Create a file called test.py (your module)
#!/usr/bin/env python |
Then create a file called app.py:
from test import * |
Related course
Python Programming Bootcamp: Go from zero to hero
python graph
Introduction
A graph in mathematics and computer science consists of “nodes” which may or may not be connected with one another. Connections between nodes are called edges. A graph can be directed (arrows) or undirected. The edges could represent distance or weight.

default graph (left), directed graph (right)
Python does not have a graph data type. To use graphs we can either use a module or implement it ourselves:
- implement graphs ourselves
- networkx module
Related course
Python Programming Bootcamp: Go from zero to hero
Graph in Python
A directed graph can be defined as:
#!/usr/bin/env python |
Graphs using networkx
The networkx software module has support for creating, manipulating graphs.
#!/usr/bin/env python |
Result:
Nodes: [‘A’, ‘C’, ‘B’]
Edges: [(‘A’, ‘C’), (‘A’, ‘B’), (‘C’, ‘B’)]
python state machine
python tree
Introduction
In computer science, a tree is a data structure that is modeled after nature. Unlike trees in nature, the tree data structure is upside down: the root of the tree is on top. A tree consists of nodes and its connections are called edges. The bottom nodes are also named leaf nodes. A tree may not have a cycle.

Python does not have built-in support for trees.
Related Course:Binary tree
A binary tree is a data structure where every node has at most two children (left and right child). The root of a tree is on top. Every node below has a node above known as the parent node.We define a class thee which has a left and right attribute. From this binary tree we define the root (top of the three) and a left and right node.
#!/usr/bin/env python |
You could then further create the tree like this:
#!/usr/bin/env python |
python binary number
python debugger
We can use debugging tools to minimize and find bugs. In this article you will learn the best Python debugging tricks.
PuDB - A console-based Python debugger

A graphical interface is shown using the PuDB terminal.
Related course:
Python Programming Bootcamp: Go from zero to hero
Installation
to install with Python 3:
|
for Python 2.x use:
|
Debugging
Start debugging with:
|
(or sudo if you don’t have the right permissions)
You can take step by step through the program. Use the n key to take a step through the program. The current variable contents are shown on the right top.

You can set breakpoints using the b key. To continue execution until the next breakpoints, press the c key.

Related course:
Python Programming Bootcamp: Go from zero to hero
PDB - The Python Debugger
The module pdb supports setting breakpoints. A breakpoint is an intentional pause of the program. where you can get more information about the programs state.
To set a breakpoint, insert the line
|
Example
A practical example:
|
We have inserted a few breakpoints in this program. The program will pause at each breakpoint (pdb.set_trace()). To view a variables contents simply type the variable name:
|
Press c or continue to go on with the programs execution until the next breakpoint
|
Related course:
Python Programming Bootcamp: Go from zero to hero
python enum
An enum (enumeration) is a set of symbolic names bound to unique constant values.
We can use enums by referring to their names, as opposed to an index number. The constant value can be any type: numeric or text. As the example below:
|
Related course
Module enum installation
To use enums module, you need Python 3.4; To install for Python 3.4:
|
For older versions (Python 2.7):
|
enum example (using enum/aenum)
We can create an Enum after importing the class Enum from either the module enum or aenum.
After importing the list
|
or as a one liner:
|
enum example (without using modules)
The old way of creating enums is:
|