category: Advanced | Python Tutorial

Category: Advanced

Logging

Logging is a very powerful way of validating your program executes correctly. In addition you can use it to debug your program.

You can log a process in your program using the module logging.

Online Courses

Example
This message would be shown in the terminal.

 
import logging
logging.warning('Something went wrong.')

Levels of severity
There are several levels of severity: DEBUG, INFO, WARNING, ERROR, CRITICAL.
You can configure a minimum level of severity, if it’s lower than the set level it’s ignored.

 
import logging

logging.basicConfig(level=logging.WARNING)
logging.debug('Debug message')
logging.error('This is an error')

Another example:

 
import logging

logging.basicConfig(level=logging.ERROR)
logging.debug('Debug message')
logging.info('Program started..')
logging.info('Loading files')
logging.error('This is an error')

While developing you could set the severity level to logging.DEBUG which will show all messages. This will help you develop faster, find bugs quicker and so on.

Upon release of your program to the market you could set it to debugging.WARNING or debugging.ERROR.

 
import logging
logging.basicConfig(level=logging.WARNING)

Line charts

Python Courses

Line chart
You can use Matplotlib to create a line chart with Python. Matplotlib is a plotting library for the Python programming language and its numerical mathematics extension numpy. This takes only a few lines:

 import numpy as np
import matplotlib.pyplot as plt

x = [2,3,4,5,7,9,13,15,17]
plt.plot(x)
plt.ylabel('Sunlight')
plt.xlabel('Time')
plt.show()


In the first two lines we include the numpy and matplotlib library. This contains logical functions to create line charts amongst others. We define a list named x with a few random numbers and we set the x and y label. Finally we call the function show() which will display the line chart. If you do not call the show() function, nothing will be shown on the screen.

matplotlib-plot

by changing the plot function call to:

plt.plot(x, 'ro-')

we create a red graph with dots, where the r in ‘ro-‘ indicates red. Changing this to ‘bo-‘ would create a blue dotted line. If you only want to display the dots, use ‘ro’ or ‘bo’ instead.

Regular expressions

Regular Expressions may be used to test if a string (Text) is according to a certain grammar. They are used to test strict grammar rules on a string.

Online Courses

Sometimes Regular Expressions are called regex or regexp. We can easily test if a string contains another string:

 >>> s = "Are you afraid of ghosts?"
>>> "ghosts" in s
True

You can also test if a string does not contain a substring:

>>> "coffee" not in s
True

Grammar
We may define a grammar, to match against any input string. Let’s say we want to match against three digits, we would define a gramamr ‘\d{3}\Z’. Example:

#!/usr/bin/python
import re

s = "123"
matcher = re.match('\d{3}\Z',s)

if matcher:
print("True")
else:
print("False")

This will out put “True” if the string s matches the grammar string.

Grammar rules
The permitted grammar for regular expressions is:

\d 	Matches a decimal digit; equivalent to the set [0-9].
\D The complement of \d. It matches any non-digit character; equivalent to the set [^0-9].
\s Matches any whitespace character; equivalent to [ \t\n\r\f\v].
\S The complement of \s. It matches any non-whitespace character; equiv. to [^ \t\n\r\f\v].
\w Matches any alphanumeric character; equivalent to [a-zA-Z0-9_].
\W Matches the complement of \w.
\b Matches the empty string, but only at the start or end of a word.
\B Matches the empty string, but not at the start or end of a word.
\\ Matches a literal backslash.

Statistics

Online Courses

Statistics with Python
Using the math library you can get various statistical values. We start by creating a list of values:

 import math

x = [1,2,15,3,6,17,8,16,8,3,10,12,16,12,9]

Five number summary
We can get the five number summary using the math library. The five number summary contains: minimum, maximum, median, mean and the standard deviation.

 import math
import numpy

x = [1,2,15,3,6,17,8,16,8,3,10,12,16,12,9]

print(numpy.min(x))
print(numpy.max(x))
print(numpy.std(x))
print(numpy.mean(x))
print(numpy.median(x))


Boxplot
This code will create a boxplot:
 import matplotlib.pyplot as plt
import numpy as np

x = [1,2,15,3,6,17,8,16,8,3,10,12,16,12,9]

plt.boxplot(x)
plt.show()

zip

The zip function takes two collections and merges them. The collections must be of equal length. Collections are : lists, tuples and the dictonaries. All examples are Python 3 code.

Related Course:

Zip lists

If we have two lists of eight elements:

a = list(range(8))
b = list(range(8))

Just having the data:

[0, 1, 2, 3, 4, 5, 6, 7]
[0, 1, 2, 3, 4, 5, 6, 7]

We can combine them:

a = range(8)
b = range(8)

ab = list(zip(a,b))
print(ab)

The list ab then contains:

python zip

All elements in the list are now pairs. If we merge three lists, we would get a pair of 3 for each element.

Note: When you zip() together two lists containing 8 elements each, the result has eight elements.

Zip dictionary

We can convert two lists to a dictionary:

 
keys=['Hawai','China']
values=['Aloha','Nihao']

ab = dict(zip(keys,values))
print(ab)

This will output:

{‘Hawai’: ‘Aloha’, ‘China’: ‘Nihao’}

 


12