python logo


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”]pycharm PyCharm, a popular Python editor

Run Python code


A python program should be save as a file with a .py extension.
Try this code:

print("Hello World!")
print("This is a Python program.")

Expected output:

Hello World!
This is a Python program

If you are using the interpreter use:

python program.py

python if string equals

python-string a string, series of characters

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"
print(s)

To get text from keyboard:


name = input("Enter name: ")
print(name)

If you use an old Python version (2.x), you need to use:


name = raw_input("Enter name: ")
print(name)

To test your version:
python –version

String Comparison


To test if two strings are equal use the equality operator (==).

#!/usr/bin/python

sentence = "The cat is brown"
q = "cat"

if q == sentence:
print('strings equal')

To test if two strings are not equal use the inequality operator (!=)

#!/usr/bin/python

sentence = "The cat is brown"
q = "cat"

if q != sentence:
print('strings equal')

If you are new to Python programming, I highly recommend this book.

Download Python Exercises

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:

String String numbering

Characters in string


The 0th index is used for the first character of a string. Try the following:

#!/usr/bin/python

s = "Hello Python"
print(s) # prints whole string
print(s[0]) # prints "H"
print(s[1]) # prints "e"

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

s = "Hello Python"
print(s[0:2]) # prints "He"
print(s[2:4]) # prints "ll"
print(s[6:]) # prints "Python"

Download Python Exercises

variables in python

python-variables
Variables in Python (x,y,z). They can be used later in the program

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
y = 1.234
z = True

You can output them to the screen using the print() function.

x = 1
y = 1.234
z = True

print(x)
print(y)
print(z)

Python supports arithmetic operations like addition (+), multiplication (*), division (/) and subtractions (-).

#!/usr/bin/env python

x = 3
y = 8

sum = x + y

print(sum)

More mathematical operations

User input


Python 3
Use the input() function to get text input, convert to a number using int() or float().

#!/usr/bin/env python

x = int(input("Enter x:"))
y = int(input("Enter y:"))

sum = x + y
print(sum)

Python 2 (old version)
You can also ask the user for input using the raw_input function:

#!/usr/bin/env python

x = int(raw_input("Enter x:"))
y = int(raw_input("Enter y:"))

sum = x + y
print(sum)

If you are new to Python programming, I highly recommend this book.

Download Python Exercises

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

l = [ "Drake", "Derp", "Derek", "Dominique" ]

print(l) # prints all elements
print(l[0]) # print first element
print(l[1]) # prints second element

Add/remove


We can use the functions append() and remove() to manipulate the list.

#!/usr/bin/python

l = [ "Drake", "Derp", "Derek", "Dominique" ]

print(l) # prints all elements
l.append("Victoria") # add element.
print(l) # print all elements
l.remove("Derp") # remove element.
l.remove("Drake") # remove element.
print(l) # print all elements.

Sort list


We can sort the list using the sort() function.

#!/usr/bin/python

l = [ "Drake", "Derp", "Derek", "Dominique" ]

print(l) # prints all elements
l.sort() # sorts the list in alphabetical order
print(l) # prints all elements

If you want to have the list in descending order, simply use the reverse() function.

#!/usr/bin/python

l = [ "Drake", "Derp", "Derek", "Dominique" ]

print(l) # prints all elements
l.sort() # sorts the list in alphabetical order
l.reverse() # reverse order.
print(l) # prints all elements

If you are new to Python programming, I highly recommend this book.

Download Python Exercises

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.



#!/usr/bin/python

x = 3
if x > 10:
print("x smaller than 10")
else:
print("x is bigger than 10 or equal")


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

print "Guess my age, you have 1 chances!"
guess = int(raw_input("Guess: "))

if guess != age:
print("Wrong!")
else:
print("Correct")

Conditional operators


A word on conditional operators

Do not confuse the assignment operator (=) with the equals operator (==).

Nesting


The most straightforward way to do multiple conditions is nesting:

Operator Description
!= not equal
== equals
> greater than
< smaller than
a = 12
b = 33

if a > 10:
if b > 20:
print("Good")

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
if guess > 10 and guess < 20:
print("In range")
else:
print("Out of range")

Sometimes you may want to use the or operator.

If you are new to Python programming, I highly recommend this book.

Download Python Exercises

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):
instructions
return value

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

def f(x):
return(x*x)

print(f(3))

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

def f(x,y):
print('You called f(x,y) with the value x = ' + str(x) + ' and y = ' + str(y))
print('x * y = ' + str(x*y))

f(3,2)

Output:


You called f(x,y) with the value x = 3 and y = 2
x * y = 6

If you are new to Python programming, I highly recommend this book.

Download Python Exercises

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.

global-local-variable A global variable (x) can be reached and modified anywhere in the code, local variable (z) exists only in block 3.

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.


def sum(x,y):
sum = x + y
return sum

print(sum(8,6))

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:


print(x)

Global variables


A global variable can be used anywhere in the code.
In the example below we define a global variable z


z = 10

def afunction():
global z
print(z)

afunction()
print(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:


z = 10

def afunction():
global z
z = 9

afunction()
print(z)

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:


z = 10

def func1():
global z
z = 3

def func2(x,y):
global z
return x+y+z

func1()
total = func2(4,5)
print(total)

If you are new to Python programming, I highly recommend this book.

Download Python Exercises

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

def f(x,y):
print('You called f(x,y) with the value x = ' + str(x) + ' and y = ' + str(y))
print('x * y = ' + str(x*y))
z = 4 # cannot reach z, so THIS WON'T WORK

z = 3
f(3,2)

but this will:

#!/usr/bin/python

def f(x,y):
z = 3
print('You called f(x,y) with the value x = ' + str(x) + ' and y = ' + str(y))
print('x * y = ' + str(x*y))
print(z) # can reach because variable z is defined in the function

f(3,2)

Let’s examine this further:

#!/usr/bin/python

def f(x,y,z):
return x+y+z # this will return the sum because all variables are passed as parameters

sum = f(3,2,1)
print(sum)

Calling functions in functions
We can also get the contents of a variable from another function:

#!/usr/bin/python

def highFive():
return 5

def f(x,y):
z = highFive() # we get the variable contents from highFive()
return x+y+z # returns x+y+z. z is reachable becaue it is defined above

result = f(3,2)
print(result)

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.

Download Python Exercises

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

items = [ "Abby","Brenda","Cindy","Diddy" ]

for item in items:
print(item)

Visualization of for loop:
for loop

The for loop can be used to repeat N times too:

#!/usr/bin/python

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

While loop


If you are unsure how many times a code should be repeated, use a while loop.
For example,


correctNumber = 5
guess = 0

while guess != correctNumber:
guess = int(input("Guess the number: "))

if guess != correctNumber:
print('False guess')

print('You guessed the correct number')

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

for x in range(1,10):
for y in range(1,10):
print("(" + str(x) + "," + str(y) + ")")

Nesting is very useful, but it increases complexity the deeper you nest.

If you are new to Python programming, I highly recommend this book.

Download Python Exercises

python range

The range() function returns of generates a sequence of numbers, starting from the lower bound to the upper bound.


range(lower_bound, upper_bound, step_size)


  • 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.

python range The python range function in the interpreter

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.


&gt;&gt;&gt; range(5)

A call to range(1,10) returns: 1,2,3,4,5,6,7,8,9


&gt;&gt;&gt; range(1,10)

Calling range(0,10,2) returns: 0,2,4,6,8


&gt;&gt;&gt; range(0,10,2)

range in python 3
To generate a list using range, add the list function


&gt;&gt;&gt; list(range(5))

We can use all parameters (lower bound, upper bound, step)


&gt;&gt;&gt; list(range(0,10,2))
[0, 2, 4, 6, 8]

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.

Download Python Exercises

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

personInfo = ("Diana", 32, "New York")
print(personInfo[0])
print(personInfo[1])

If you want to assign multiple variables at once, you can use tuples:

#!/usr/bin/env python

name,age,country,career = ('Diana',32,'Canada','CompSci')
print(country)

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

x = (3,4,5,6)
x = x + (1,2,3)
print(x)

If you are new to Python programming, I highly recommend this book.

Download Python Exercises

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

words = {}
words["Hello"] = "Bonjour"
words["Yes"] = "Oui"
words["No"] = "Non"
words["Bye"] = "Au Revoir"

print(words["Hello"])
print(words["No"])

Output:


Bonjour
Non

We are by no means limited to single word defintions in the value part. A demonstration:

#!/usr/bin/python

dict = {}
dict['Ford'] = "Car"
dict['Python'] = "The Python Programming Language"
dict[2] = "This sentence is stored here."

print(dict['Ford'])
print(dict['Python'])
print(dict[2])

Output:


Car
The Python Programming Language
This sentence is stored here.

Manipulating the dictionary


We can manipulate the data stored in a dictionairy after declaration.  This is shown in the example below:

#!/usr/bin/python

words = {}
words["Hello"] = "Bonjour"
words["Yes"] = "Oui"
words["No"] = "Non"
words["Bye"] = "Au Revoir"

print(words) # print key-pairs.
del words["Yes"] # delete a key-pair.
print(words) # print key-pairs.
words["Yes"] = "Oui!" # add new key-pair.
print(words) # print key-pairs.

Output:


{'Yes': 'Oui', 'Bye': 'Au Revoir', 'Hello': 'Bonjour', 'No': 'Non'}
{'Bye': 'Au Revoir', 'Hello': 'Bonjour', 'No': 'Non'}
{'Yes': 'Oui!', 'Bye': 'Au Revoir', 'Hello': 'Bonjour', 'No': 'Non'}

If you are new to Python programming, I highly recommend this book.

Download Python Exercises

python cast

Python determines the datatype automatically, to illustrate:


x = 3
y = "text"

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
y = 2.15315315313532

print("We have defined two numbers,")
print("x = " + str(x))
print("y = " + str(y))

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"
b = "133.1112223"

c = float(a) + float(b)
print(c)

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:

Download Python Exercises

python random number between 1 and 100

Using the random module, we can generate pseudo-random numbers. The function random() generates a random number between zero and one [0, 0.1 .. 1].  Numbers generated with this module are not truly random but they are enough random for most purposes.

Related Course:
Python Programming Bootcamp: Go from zero to hero

Random number between 0 and 1.
We can generate a (pseudo) random floating point number with this small code:

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 *

print(random()) # Generate a pseudo-random number between 0 and 1.

Generate a random number between 1 and 100
To generate a whole number (integer) between one and one hundred use:

from random import *

print(randint(1, 100)) # Pick a random number between 1 and 100.

This will printa random integer. If you want to store it in a variable you can use:

from random import *

x = randint(1, 100) # Pick a random number between 1 and 100.
print(x)

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 *

print(uniform(1, 10))

Picking a random item from a list

Fun with lists
We can shuffle a list with this code:

from random import *

items = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
shuffle(items)
print(items)

To pick a random number from a list:

from random import *

items = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

x = sample(items, 1) # Pick a random item from the list
print(x[0])

y = sample(items, 4) # Pick 4 random items from the list
print(y)

We can do the same thing with a list of strings:

from random import *

items = ['Alissa','Alice','Marco','Melissa','Sandra','Steve']

x = sample(items, 1) # Pick a random item from the list
print(x[0])

y = sample(items, 4) # Pick 4 random items from the list
print(y)

If you are new to Python programming, I highly recommend this book.

Download Python Exercises

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")
lines = f.readlines()
print(lines)

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")
lines = f.readlines()

for line in lines:
print(line, end="")

Another option is to remove the newline characters with the replace() method.

f = open("test.py","r")
lines = f.readlines()

for line in lines:
line = line.replace("\n","")
print(line)

read file with keyword

The with keyword can be used to read files too. This automatically closes your file.

#!/usr/bin/env python

# Define a filename.
filename = "bestand.py"

# Open the file as f.
# The function readlines() reads the file.
with open(filename) as f:
content = f.readlines()

# Show the file contents line by line.
# We added the comma to print single newlines and not double newlines.
# This is because the lines contain the newline character '\n'.
for line in content:
print(line),

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

# Define a filename.
filename = "bestand.py"

# Open the file as f.
# The function readlines() reads the file.
with open(filename) as f:
content = f.read().splitlines()

# Show the file contents line by line.
# We added the comma to print single newlines and not double newlines.
# This is because the lines contain the newline character '\n'.
for line in content:
print(line)

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
import os.path

# Define a filename.
filename = "bestand.py"

if not os.path.isfile(filename):
print('File does not exist.')
else:
# Open the file as f.
# The function readlines() reads the file.
with open(filename) as f:
content = f.read().splitlines()

# Show the file contents line by line.
# We added the comma to print single newlines and not double newlines.
# This is because the lines contain the newline character '\n'.
for line in content:
print(line)

If you are new to Python programming, I highly recommend this book.

Download Python Exercises

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

# Filename to write
filename = "newfile.txt"

# Open the file with writing permission
myfile = open(filename, 'w')

# Write a line to the file
myfile.write('Written with Python\n')

# Close the file
myfile.close()

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

# Filename to append
filename = "newfile.txt"

# The 'a' flag tells Python to keep the file contents
# and append (add line) at the end of the file.
myfile = open(filename, 'a')

# Add the line
myfile.write('Written with Python\n')

# Close the file
myfile.close()

Parameters


A summary of parameters:

If you are new to Python programming, I highly recommend this book.

Download Python Exercises

python class

Introduction


Technology always evolves. What are classes and where do they come from?

1. Statements:
In the very early days of computing, programmers wrote only commands.

2. Functions:
Reusable group of statements, helped to structure that code and it improved readability.

3. Classes:
Classes are used to create objects which have functions and variables. Strings are examples of objects: A string book has the functions book.replace() and book.lowercase(). This style is often called object oriented programming.

Lets take a dive!

Python Courses:
Python Programming Bootcamp: Go from zero to hero

Python class


We can create virtual objects in Python. A virtual object can contain variables and methods.  A program may have many different types and are created from a class. Example:

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:
name = ""

def __init__(self, name):
self.name = name

def sayHello(self):
print("Hello, my name is " + self.name)

# create virtual objects
james = User("James")
david = User("David")
eric = User("Eric")

# call methods owned by virtual objects
james.sayHello()
david.sayHello()

Run this program. In this code we have 3 virtual objects: james, david and eric.  Each object is instance of the User class.

python class: creation of objects Python Class: create objects

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):
self.bean = self.bean + 1

def removeBean(self):
self.bean = self.bean - 1

We do the same for the variable water. As shown below:

class CoffeeMachine:
name = ""
beans = 0
water = 0

def __init__(self, name, beans, water):
self.name = name
self.beans = beans
self.water = water

def addBean(self):
self.beans = self.beans + 1

def removeBean(self):
self.beans = self.beans - 1

def addWater(self):
self.water = self.water + 1

def removeWater(self):
self.water = self.water - 1

def printState(self):
print "Name = " + self.name
print "Beans = " + str(self.beans)
print "Water = " + str(self.water)

pythonBean = CoffeeMachine("Python Bean", 83, 20)
pythonBean.printState()
print ""
pythonBean.addBean()
pythonBean.printState()

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:


Name = Python Bean
Beans = 83
Water = 20

Name = Python Bean
Beans = 84
Water = 20

If you are new to Python programming, I highly recommend this book.

Download Exercises
 

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:


class Animal:
def __init__(self,name):
self.name = name

def walk(self):
print(self.name + ' walks.')

duck = Animal('Duck')
duck.walk()

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 = ..).

python class Python class and object drawn using the modeling language UML

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:


class Animal:
def __init__(self,name):
self.name = name

def walk(self):
print(self.name + ' walks.')

duck = Animal('Duck')
duck.walk()

rhino = Animal('African Rhino')
rhino.walk()

If you are new to Python programming, I highly recommend this book.

Download Exercises

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

encapsulation encapsulation. Restricted accesss to methods or variables

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

class Car:

def __init__(self):
self.__updateSoftware()

def drive(self):
print('driving')

def __updateSoftware(self):
print('updating software')

redcar = Car()
redcar.drive()
#redcar.__updateSoftware() not accesible from object.

This program will output:

updating software
driving

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

encapsulation-example Class with 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

class Car:

__maxspeed = 0
__name = ""

def __init__(self):
self.__maxspeed = 200
self.__name = "Supercar"

def drive(self):
print('driving. maxspeed ' + str(self.__maxspeed))

redcar = Car()
redcar.drive()
redcar.__maxspeed = 10 # will not change variable because its private
redcar.drive()

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

class Car:

__maxspeed = 0
__name = ""

def __init__(self):
self.__maxspeed = 200
self.__name = "Supercar"

def drive(self):
print('driving. maxspeed ' + str(self.__maxspeed))

def setMaxSpeed(self,speed):
self.__maxspeed = speed

redcar = Car()
redcar.drive()
redcar.setMaxSpeed(320)
redcar.drive()

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:

Other programming languages have protected class methods too, but Python does not.

Encapsulation gives you more control over the degree of coupling in your code, it allows a class to change its implementation without affecting other parts of the code.

If you are new to Python programming, I highly recommend this book.

Download Exercises

In Python you can define a method in such a way that there are multiple ways to call it.

Given a single method or function, we can specify the number of parameters ourself.

Depending on the function definition, it can be called with zero, one, two or more parameters.

This is known as method overloading. Not all programming languages support method overloading, but Python does.

Related course
Python Programming Bootcamp: Go from zero to hero

Method overloading example


We create a class with one method sayHello(). The first parameter of this method is set to None, this gives us the option to call it with or without a parameter.

An object is created based on the class, and we call its method using zero and one parameter.

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
method overloading Several ways to call a method (method overloading)
#!/usr/bin/env python

class Human:

def sayHello(self, name=None):

if name is not None:
print('Hello ' + name)
else:
print('Hello ')


# Create instance
obj = Human()

# Call the method
obj.sayHello()

# Call the method with a parameter
obj.sayHello('Guido')

Output:

Hello
Hello Guido

To clarify method overloading, we can now call the method sayHello() in two ways:

obj.sayHello()
obj.sayHello('Guido')

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.

Download Exercises

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:
name = ""

def __init__(self, name):
self.name = name

def printName(self):
print("Name = " + self.name)

brian = User("brian")
brian.printName()

This creates one instance called brian which outputs its given name. We create another class called Programmer.

class Programmer(User):

def __init__(self, name):
self.name = name

def doPython(self):
print("Programming Python")

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:
name = ""

def __init__(self, name):
self.name = name

def printName(self):
print("Name = " + self.name)

class Programmer(User):
def __init__(self, name):
self.name = name

def doPython(self):
print("Programming Python")

brian = User("brian")
brian.printName()

diana = Programmer("Diana")
diana.printName()
diana.doPython()

The output:

Name  = brian
Name = Diana
Programming Python

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.

Download Exercises

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):
def sound(self):
print("Groarrr")

class Dog(object):
def sound(self):
print("Woof woof!")

def makeSound(animalType):
animalType.sound()


bearObj = Bear()
dogObj = Dog()

makeSound(bearObj)
makeSound(dogObj)

Output:

Groarrr
Woof woof!

Polymorphism with abstract class (most commonly used)

polymorphism example Polymorphism visual.
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:
print document.name + ': ' + document.show()

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:
def __init__(self, name):
self.name = name

def show(self):
raise NotImplementedError("Subclass must implement abstract method")

class Pdf(Document):
def show(self):
return 'Show pdf contents!'

class Word(Document):
def show(self):
return 'Show word contents!'

documents = [Pdf('Document1'),
Pdf('Document2'),
Word('Document3')]

for document in documents:
print document.name + ': ' + document.show()

Output:

Document1: Show pdf contents!
Document2: Show pdf contents!
Document3: Show word 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

polymorphism-example Structure in abstract class, implementation in other classes

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:
def drive abstract, no implementation.
def stop abstract, no implementation.

class Sportscar(Car):
def drive: implementation of sportscar
def stop: implementation of sportscar

class Truck(Car):
def drive: implementation of truck
def stop: implementation of truck


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:
def __init__(self, name):
self.name = name

def drive(self):
raise NotImplementedError("Subclass must implement abstract method")

def stop(self):
raise NotImplementedError("Subclass must implement abstract method")

class Sportscar(Car):
def drive(self):
return 'Sportscar driving!'

def stop(self):
return 'Sportscar braking!'

class Truck(Car):
def drive(self):
return 'Truck driving slowly because heavily loaded.'

def stop(self):
return 'Truck braking!'

cars = [Truck('Bananatruck'),
Truck('Orangetruck'),
Sportscar('Z3')]

for car in cars:
print car.name + ': ' + car.drive()

Output:

Bananatruck: Truck driving slowly because heavily loaded.
Orangetruck: Truck driving slowly because heavily loaded.
Z3: Sportscar driving!

If you are new to Python programming, I highly recommend this book.

Download Exercises

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

class Human:

def __init__(self):
self.name = 'Guido'
self.head = self.Head()

class Head:
def talk(self):
return 'talking...'

if __name__ == '__main__':
guido = Human()
print(guido.name)
print(guido.head.talk())

Output:

Guido
talking...

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

class Human:

def __init__(self):
self.name = 'Guido'
self.head = self.Head()
self.brain = self.Brain()

class Head:
def talk(self):
return 'talking...'

class Brain:
def think(self):
return 'thinking...'

if __name__ == '__main__':
guido = Human()
print(guido.name)
print(guido.head.talk())
print(guido.brain.think())

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.

  1. Inner class has a local scope
  2. 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.

Download Exercises

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")
obj.drive()

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.


class Car(object):

def factory(type):
if type == "Racecar":
return Racecar()
if type == "Van":
return Van()

factory = staticmethod(factory)

class Racecar(Car):
def drive(self):
print("Racecar driving.")

class Van(Car):
def drive(self):
print("Van driving.")

# Create object using factory.
obj = Car.factory("Racecar")
obj.drive()

Output:

Racecar driving.

If you are new to Python programming, I highly recommend this book.

Download Exercises

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

def sum(list):
sum = 0

# Add every number in the list.
for i in range(0, len(list)):
sum = sum + list[i]

# Return the sum.
return sum

print(sum([5,7,3,8,10]))

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

def sum(list):
if len(list) == 1:
return list[0]
else:
return list[0] + sum(list[1:])

print(sum([5,7,3,8,10]))

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

def factorial(n):
if n == 1:
return 1
else:
return n * factorial(n-1)

print(factorial(3))

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

def factorial(n):
if n == 1:
return 1
else:
return n * factorial(n-1)

print(factorial(3000))

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
import sys

sys.setrecursionlimit(5000)

def factorial(n):
if n == 1:
return 1
else:
return n * factorial(n-1)

print(factorial(3000))

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

# print a log message to the console.
logging.warning('This is a warning!')

This will output:

WARNING:root:This is a warning!

We can easily output to a file:

import logging

logging.basicConfig(filename='program.log',level=logging.DEBUG)
logging.warning('An example message.')
logging.warning('Another message')

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:

The default logging level is warning, which implies that other messages are ignored. If you want to print debug or info log messages you have to change the logging level like so:

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

logging.basicConfig(level=logging.DEBUG)
logging.debug('Debug message')

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

logging.basicConfig(format='%(asctime)s %(message)s', level=logging.DEBUG)
logging.info('Logging app started')
logging.warning('An example logging message.')
logging.warning('Another log message')

Output:

2015-06-25 23:24:01,153 Logging app started
2015-06-25 23:24:01,153 An example message.
2015-06-25 23:24:01,153 Another message

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

from subprocess import Popen, PIPE

process = Popen(['cat', 'test.py'], stdout=PIPE, stderr=PIPE)
stdout, stderr = process.communicate()
print stdout

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)
# Run the command described by args.
# Wait for command to complete, then return the returncode attribute.

In the example below the full command would be “ls -l”

#!/usr/bin/env python

import subprocess
subprocess.call(["ls", "-l"])

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)
# Run command with arguments and return its output as a byte string.

Example usage:

#!/usr/bin/env python
import subprocess

s = subprocess.check_output(["echo", "Hello World!"])
print("s = " + s)

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 origin 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

f = lambda x : 2 * x
print f(3)

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

f = lambda x: x > 10
print(f(2))
print(f(12))

map function


The definition of map is map(function,iterable). It applies a function to every item in the iteratable. We can use map() to on a lambda function with a list:

#!/usr/bin/env python

list = [1,2,3,4,5]
squaredList = map(lambda x: x*x, list)
print(squaredList)

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 elmeents for which the function returns True. Example:

#!/usr/bin/env python

list = [1,2,3,4,5,6,7,8,9,10]
newList = filter(lambda x: x % 2 == 0, list)
print(newList)

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

list = [1,2,3,4,5]
s = reduce(lambda x,y: x+y, list)
print(s)

In this case the expression is always true, thus it simply sums up the elements of the list. Another example:

#!/usr/bin/env python

list = [10,6,7,5,2,1,8,5]
s = reduce(lambda x,y: x if (x > y) else y, list)
print(s)


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

x = set(["Postcard", "Radio", "Telegram"])
print(x)

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

x = set(["Postcard", "Radio", "Telegram", "Postcard"])
print(x)

Simple notation


If you use Python version 2.6 or a later version, you can use a simplified notation:

#!/usr/bin/env python

x = set(["Postcard", "Radio", "Telegram"])
print(x)

y = {"Postcard","Radio","Telegram"}
print(y)

Set Methods


Clear elements from set
To remove all elements from sets:

#!/usr/bin/env python

x = set(["Postcard", "Radio", "Telegram"])
x.clear()
print(x)

Add elements to a set
To add elements to a set:

#!/usr/bin/env python

x = set(["Postcard", "Radio", "Telegram"])
x.add("Telephone")
print(x)

Remove elements to a set
To remove elements to a set:

!/usr/bin/env python

x = set(["Postcard", "Radio", "Telegram"])
x.remove("Radio")
print(x)

Difference between two sets
To find the difference between two sets use:

#!/usr/bin/env python
x = set(["Postcard", "Radio", "Telegram"])
y = set(["Radio","Television"])
print( x.difference(y) )
print( y.difference(x) )

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

x = set(["a","b","c","d"])
y = set(["c","d"])
print( x.issubset(y) )<b>
</b>

Super-set
To test if a set is a super-set:

#!/usr/bin/env python

x = set(["a","b","c","d"])
y = set(["c","d"])
print( x.issuperset(y) )

Intersection
To test for intersection, use:

#!/usr/bin/env python

x = set(["a","b","c","d"])
y = set(["c","d"])
print( x.intersection(y) )

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
import sys

print(dir(sys))

Result:


['__displayhook__', '__doc__', '__egginsert', '__excepthook__', '__name__', '__package__', '__plen', '__stderr__', '__stdin__',
'__stdout__', '_clear_type_cache', '_current_frames', '_getframe', '_mercurial', '_multiarch', 'api_version', 'argv',
'builtin_module_names', 'byteorder', 'call_tracing', 'callstats', 'copyright', 'displayhook', 'dont_write_bytecode',
'exc_clear', 'exc_info', 'exc_type', 'excepthook', 'exec_prefix', 'executable', 'exit', 'flags', 'float_info', 'float_repr_style'
, 'getcheckinterval', 'getdefaultencoding', 'getdlopenflags', 'getfilesystemencoding', 'getprofile', 'getrecursionlimit',
'getrefcount', 'getsizeof', 'gettrace', 'hexversion', 'long_info', 'maxint', 'maxsize', 'maxunicode', 'meta_path', 'modules',
'path', 'path_hooks', 'path_importer_cache', 'platform', 'prefix', 'py3kwarning', 'pydebug', 'setcheckinterval', 'setdlopenflags'
, 'setprofile', 'setrecursionlimit', 'settrace', 'stderr', 'stdin', 'stdout', 'subversion', 'version', 'version_info',
'warnoptions']

Create a Module


You can create your own module in these steps:

Create a file called test.py (your module)

#!/usr/bin/env python

def add(a,b):
return a+b


Then create a file called app.py:

from test import *

print('hello')
print(add(5,2))

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.

graph mathematics
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

graph = {'A': ['B', 'C'],
'B': ['C', 'A'],
'C': ['D'],
'D': ['A']}

print(graph)

Graphs using networkx


The networkx software module has support for creating, manipulating graphs.

#!/usr/bin/env python
import networkx as nx

G=nx.Graph()
G.add_node("A")
G.add_node("B")
G.add_node("C")
G.add_edge("A","B")
G.add_edge("B","C")
G.add_edge("C","A")

print("Nodes: " + str(G.nodes()))
print("Edges: " + str(G.edges()))

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.

 

tree A tree with eight nodes. The root of the tree (5) is on top.

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
class Tree(object):
def __init__(self):
self.left = None
self.right = None
self.data = None

root = Tree()
root.data = "root"
root.left = Tree()
root.left.data = "left"
root.right = Tree()
root.right.data = "right"

print(root.left.data)

You could then further create the tree like this:

#!/usr/bin/env python
class Tree(object):
def __init__(self):
self.left = None
self.right = None
self.data = None

root = Tree()
root.data = "root"
root.left = Tree()
root.left.data = "left"
root.right = Tree()
root.right.data = "right"

root.left.left = Tree()
root.left.left.data = "left 2"
root.left.right = Tree()
root.left.right.data = "left-right"

 

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

python-debugging-pudb Python Debug with PuDB

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:


sudo pip3 install pudb

for Python 2.x use:


sudo pip install pudb

Debugging
Start debugging with:


$ pudb3 program.py

(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.

pudb-debug debug with python

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

python-breakpoint Breakpoint in Python program

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


pdb.set_trace()

Example
A practical example:


import pdb

x = 3
y = 4
pdb.set_trace()

total = x + y
pdb.set_trace()

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:


$ python3 program.py
(Pdb) x
3
(Pdb) y
4
(Pdb) total
*** NameError: name 'total' is not defined
(Pdb)

Press c or continue to go on with the programs execution until the next breakpoint


(Pdb) c
--Return--
> program.py(7)<module>()->None
-> total = x + y
(Pdb) total
7

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:


currency = enum(EUR='Euro',USD='United States Dollar', GBP='Great British Pound')
print(currency.USD)

Related course

Module enum installation
To use enums module, you need Python 3.4; To install for Python 3.4:


sudo pip install enum34

For older versions (Python 2.7):


sudo pip install aenum

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


#from enum import Enum
from aenum import Enum

class Numbers(Enum):
ONE = 1
TWO = 2
THREE = 3
FOUR = 4

print(Numbers.ONE.value)
print(Numbers.THREE.value)

or as a one liner:


#from enum import Enum
from aenum import Enum

class Numbers(Enum):
ONE, TWO, THREE, FOUR = 1,2,3,4

print(Numbers.ONE.value)
print(Numbers.THREE.value)

enum example (without using modules)
The old way of creating enums is:


def enum(**enums):
return type('Enum', (), enums)

Numbers = enum(ONE=1,TWO=2, THREE=3, FOUR=4, FIVE=5, SIX=6)
print(Numbers.ONE)