Monthly Archives: May 2013

Decimal and Fraction Numbers in Python

Decimal and Fraction Numbers in Python

We should remember not only integers and floats but also other numeric types: decimal numbers (fixed-precision floating-point numbers) and fraction numbers (rational numbers with both a numerator and a denominator). We can use them in the situation where integers and floats aren’t too good.

When we deal with numerals in a standard way:

>>> 1/4
0.25
>>> 4/7
0.5714285714285714
>>> 6/5
1.2

But we want more.

Fractions
>>> import fractions
>>> dir(fractions)
[‘Decimal’, ‘Fraction’, ‘_PyHASH_INF’, ‘_PyHASH_MODULUS’, ‘_RATIONAL_FORMAT’, ‘_
_all__’, ‘__builtins__’, ‘__cached__’, ‘__doc__’, ‘__file__’, ‘__initializing__’
, ‘__loader__’, ‘__name__’, ‘__package__’, ‘gcd’, ‘math’, ‘numbers’, ‘operator’,
 ‘re’, ‘sys’]
>>>

Let’s try use it:

>>> s = fractions.Fraction(1,2)
>>> s
Fraction(1, 2)
>>> s + 4
Fraction(9, 2)
>>> s – 2
Fraction(-3, 2)
>>> t = fractions.Fraction(3,2)
>>> t
Fraction(3, 2)
>>> t * 2
Fraction(3, 1)
>>> t / 7
Fraction(3, 14)
>>> u = s + t
>>> u
Fraction(2, 1)
>>> u + fractions.Fraction(1, 6)
Fraction(13, 6)
>>> fractions.Fraction(1,2) +  fractions.Fraction(1,2)
Fraction(1, 1)
>>>

Decimals
>>> import decimal
>>> dir(decimal)
[‘BasicContext’, ‘Clamped’, ‘Context’, ‘ConversionSyntax’, ‘Decimal’, ‘DecimalEx
ception’, ‘DecimalTuple’, ‘DefaultContext’, ‘DivisionByZero’, ‘DivisionImpossibl
e’, ‘DivisionUndefined’, ‘ExtendedContext’, ‘FloatOperation’, ‘HAVE_THREADS’, ‘I
nexact’, ‘InvalidContext’, ‘InvalidOperation’, ‘MAX_EMAX’, ‘MAX_PREC’, ‘MIN_EMIN
‘, ‘MIN_ETINY’, ‘Overflow’, ‘ROUND_05UP’, ‘ROUND_CEILING’, ‘ROUND_DOWN’, ‘ROUND_
FLOOR’, ‘ROUND_HALF_DOWN’, ‘ROUND_HALF_EVEN’, ‘ROUND_HALF_UP’, ‘ROUND_UP’, ‘Roun
ded’, ‘Subnormal’, ‘Underflow’, ‘__doc__’, ‘__file__’, ‘__initializing__’, ‘__lo
ader__’, ‘__name__’, ‘__package__’, ‘__version__’, ‘getcontext’, ‘localcontext’,
 ‘setcontext’]
>>>

Let’s try use it:

>>> l = decimal.Decimal(234.45)
>>> l
Decimal(‘234.44999999999998863131622783839702606201171875’)
>>> l + 345
Decimal(‘579.4499999999999886313162278’)
>>> l – 34
Decimal(‘200.4499999999999886313162278’)

We should use ‘ or “:

>>> l = decimal.Decimal(‘234.45’)
>>> l
Decimal(‘234.45’)
>>>

Let’s see some operations:
>>> k = decimal.Decimal(“2.00”)
>>> k
Decimal(‘2.00’)
>>> n = decimal.Decimal(“24.00”)
>>> n
Decimal(‘24.00’)
>>> n / k
Decimal(’12’)
>>>

 

Nested Dictionaries in Python

Nested Dictionaries in Python

We can nest dictionaries like lists.

>>> m = {‘nazwa’: {‘imię’: ‘Edek’, ‘nazwisko’: ‘Woliński’, ‘nick’: ‘Wolan’}, ‘żona’:
 ‘Anna’, ‘dzieci’: {‘syn’: ‘Adam’, ‘córka’: “Hela”}}
>>> m
{‘dzieci’: {‘córka’: ‘Hela’, ‘syn’: ‘Adam’}, ‘nazwa’: {‘imię’: ‘Edek’, ‘nic
k’: ‘Wolan’, ‘nazwisko’: ‘Woliński’}, ‘żona’: ‘Anna’}
>>>

We can retrieve an item very easy:

>>> m[‘nazwa’]
{‘imię’: ‘Edek’, ‘nick’: ‘Wolan’, ‘last’: ‘Woliński’}
>>> m[‘nazwa’][‘nick’]
‘Wolan’
>>> m[‘nazwa’][‘last’]
‘Woliński’
>>>

Matrixes and Comprehension Expressions in Python

Matrixes and Comprehension Expressions in Python

We can nesting in Python. It’s especially useful for lists. We can get the 3 x 3 matrix:

>>> e = [[10,20,30], [40,50,60], [70,80,90]]
>>> e
[[10, 20, 30], [40, 50, 60], [70, 80, 90]]
>>>

We can use it in the following way:

>>> e[2]
[70, 80, 90]

We have one row only, but we can do that:
>>> e[2][2]
90
>>>
But what with columns? We need to extract the second column in our matrix.

>>> f = [g[2] for g in e]
>>> f
[30, 60, 90]
>>> h = [g[0] for g in e]
>>> h
[10, 40, 70]
>>>
We can even do more with comprehension:

>>> f = [g[2] * 3 + 4 for g in e]
>>> f
[94, 184, 274]
>>> h = [g[0] / 4 – 1 for g in e]
>>> h
[1.5, 9.0, 16.5]
>>>

We can create a generator using a matrix:

>>> i = (sum(j) for j in e)
>>> i
<generator object <genexpr> at 0x00D078F0>
>>> next(i)
60
>>> next(i)
150
>>> next(i)
240
>>>

And we can do many other operations with matrixes.

How Python works

How Python works

Python

———————-

module          module

——————————————————————

statement       statement       statement        statement

————————————————————————————————

expression      expression       expression       expression      expression       expression

——————————————————————————————————————————————–

object            object          object           object         object           object         object           object

CPython

It’s true for CPython that’s the standard version we use with the Python name. It’s based on ANSI C.

Source————————->Byte Code—————————>Runtime

plik.py                                            plik.pyc                                       Python Virtual Machine

writing                                            compilation                               interpretation

dependent on you                 automatic, independent            dependent on the system we use

Python looks for a plik.pyc, and then plik.py if the first one isn’t present.

Jython

Source—————————–>Similar to Java

plik.py

IronPython

Source—————————–>Similar to .NET

plik.py

To catch the output in a file:

python plik.py > plik.txt

To catch the input in a file:

python plik.py < plik.txt

Usually, we can run the file in Windows:
python plik.py
But when we have not set the PATH environment variable, we must provide the full path to our Python interpreter:
D:\python33\python plik.py

On new Windows, however, we can write (if our PATH is set):

plik.py

We can provide the full path to the folder with our files (if our PATH isn’t set):
python D:\python33\scripts\plik.py
If our PATH isn’t set for Python’s directory, Python, and our file is in other folder than we are working in, we use:

D:\Python33\python D:\python33\scripts\plik.py

There are plik.py and plik.pyw. The latter will display only a window made by our script, not DOS console window as usual. Such a file has a special behavior on Windows. It’s used for user interfaces.

We can import a Python module only once per session (process). We can use import many times — no changed will be. But we can reload the module.
>>> from imp import reload
>>> reload(plik)

A module is a package of variable names that is known namespace. These name in this package are know attributes (an attribute is a variable name that is attached to any object).

We have the following module:

python plik.py

And we can do:

Get the whole module:
>>> import plik
We like Polish. We love Polish.
>>>
>>> plik.b, plik.c
(‘We like Polish.’, ‘We love Polish.’)
>>>

Copy the names:
>>> from plik import a, b
>>> b, c
(‘We like Polish.’, ‘We love Polish.’)

We can see the values in parentheses because they are tuples. dir can get all names in a module:
>>> dir(plik)
[‘__builtins__’, ‘__doc__’, ‘__file__’, ‘__name__’, ‘__package__’, ‘a’, ‘b’]

A program is composed of many modules linked together by import statements. Each  module is a self-contained package of variables that is a namespace. One module doesn’t see the names in another file. However, we can import them

Remember — import is better than from!

When Python imports, it started to seek in sys.path – a Python list of directory name strings in the sys module, which is initialized form PYTHONPATH, and set of standard directories.

We can run the code in our module using:

exec(open(‘module.py’).read())

We don’t need import and reload our module. exec runs the current version of the file without reloading.
>>> exec(open(‘plik.py’).read())
We like Polish.
We love Polish.
>>> exec(open(‘plik.py’).read())
We like Polish.
We love Polish.
We worship Polish.
>>>

exec runs the module anew. It can overwrite variable we are using (like from). It’s better not to use that.

Problem with Starting IDLE for Python

Problem with Starting IDLE for Python

Sometimes we have problem with IDLE for Python, so we must start it with a system command line that forces it to run in single-process mode (without a user-code subprocess). Using -n flag we can force this mode.

D:\Python33\Lib\idlelib idle.py -n

For example, I use the following:

D:\Python33\Lib\idlelib>idle.py -n

pt

So we see in our IDLE:

Python 3.3.0 (v3.3.0:bd8afb90ebf2, Sep 29 2012, 10:55:48) [MSC v.1600 32 bit (Intel)] on win32
Type “copyright”, “credits” or “license()” for more information.
==== No Subprocess ====
>>>

You see that there’s no subprocess.

re Module in Python

re Module in Python

>>> dir(re)
[‘A’, ‘ASCII’, ‘DEBUG’, ‘DOTALL’, ‘I’, ‘IGNORECASE’, ‘L’, ‘LOCALE’, ‘M’, ‘MULTIL
INE’, ‘S’, ‘Scanner’, ‘T’, ‘TEMPLATE’, ‘U’, ‘UNICODE’, ‘VERBOSE’, ‘X’, ‘__all__’
, ‘__builtins__’, ‘__cached__’, ‘__doc__’, ‘__file__’, ‘__initializing__’, ‘__lo
ader__’, ‘__name__’, ‘__package__’, ‘__version__’, ‘_alphanum_bytes’, ‘_alphanum
_str’, ‘_compile’, ‘_compile_repl’, ‘_expand’, ‘_pattern_type’, ‘_pickle’, ‘_sub
x’, ‘compile’, ‘copyreg’, ‘error’, ‘escape’, ‘findall’, ‘finditer’, ‘functools’,
 ‘match’, ‘purge’, ‘search’, ‘split’, ‘sre_compile’, ‘sre_parse’, ‘sub’, ‘subn’,
 ‘sys’, ‘template’]
>>>

Regular expressions use the following characters:

., ^, $, *, +, ?, {, }, [, ], \, |, (, )

findall

>>> z = “We love learning Polish because it is a very interesting language”
>>> z
‘We love learning Polish because it is a very interesting language’
>>> re.findall(“i”, z)
[‘i’, ‘i’, ‘i’, ‘i’, ‘i’, ‘i’]
>>> re.findall(“i.”, z)
[‘in’, ‘is’, ‘it’, ‘is’, ‘in’, ‘in’]
>>> re.findall(“^W”, z)
[‘W’]
>>> re.findall(“^P”, z)
[]
>>> re.findall(“guage$”, z)
[‘guage’]
>>> re.findall(“because$”, z)
[]
>>> re.findall(“i[a-z]?”, z)
[‘in’, ‘is’, ‘it’, ‘is’, ‘in’, ‘in’]
>>> re.findall(“i[a-z]??”, z)
[‘i’, ‘i’, ‘i’, ‘i’, ‘i’, ‘i’]
>>>

split

>>> re.split(” “, z)
[‘We’, ‘love’, ‘learning’, ‘Polish’, ‘because’, ‘it’, ‘is’, ‘a’, ‘very’, ‘intere
sting’, ‘language’]
>>> re.split(” “, z)

search

>>>
>>> b = re.search(“Polish”, z)
>>> b
<_sre.SRE_Match object at 0x00C1DA30>

>>> print(b.start(), b.end(), b.group(0))
17 23 Polish
>>>

>>> c = re.search(“in”, z)
>>> print(c.start(), c.end(), c.group(0))
13 15 in

We can search in our string with the pattern we have. Then, we can print it using the start of the string, the end of the string, and the value of the pattern. When there’s 0, we will get the first value, when there’s 1, we will get the second, and so on.

sub

>>> q = re.sub(“Polish”, “Russian”, z)
>>> print(q)
We love learning Russian because it is a very interesting language
>>>

We can change something in our string, replacing words.

match

>>> f = re.match(“^H”, “Hello world”)
>>> f.group(0)
‘H’
>>>

We can match anything in our string.

fnmatch Module in Python

fnmatch Module in Python

>>> dir(fnmatch)
[‘__all__’, ‘__builtins__’, ‘__cached__’, ‘__doc__’, ‘__file__’, ‘__initializing
__’, ‘__loader__’, ‘__name__’, ‘__package__’, ‘_compile_pattern’, ‘filter’, ‘fnm
atch’, ‘fnmatchcase’, ‘functools’, ‘os’, ‘posixpath’, ‘re’, ‘translate’]
>>>

We can see that this module contains other modules: re and os. Thanks to the fnmatch module, we can filter folders and files with shell patterns.

fnmatch(name, pattern) -> True if the name is matching the pattern

>>> fnmatch.fnmatch(“Kasia”, “K*s*a”)
True
>>> fnmatch.fnmatch(“Ala”, “?l?”)
True
>>> fnmatch.fnmatch(“Ala”, “?le”)
False
>>>

>>> for c in os.listdir(“D:/”):
…     fnmatch.fnmatch(c,”*.txt”)

False
True
False
True
True
False
False
False
False
False
False
False
False
False
False
True
False
False
False
>>>

It’s not exactly what we need. We should do something else:

>>> for c in os.listdir(“D:/”):
…     if fnmatch.fnmatch(c, “*.txt”):
…             print(c)

artyk.txt
derek.txt
dereka.txt
pliczek.txt
>>>

That’s it!

filter

>>> v = [“derek.txt”, “eta.csv”, “zeta.csv”, “pliczek.txt”]
>>> v
[‘derek.txt’, ‘eta.csv’, ‘zeta.csv’, ‘pliczek.txt’]

>>> fnmatch.filter(v, “*.csv”)
[‘eta.csv’, ‘zeta.csv’]
>>>

>>> fnmatch.filter(v, “*.txt”)
[‘derek.txt’, ‘pliczek.txt’]
>>>

We can use the filter function to filter a list against a pattern.

translate

>>> j = fnmatch.translate(“*.txt, c[eao]*.txt, t?.csv”)
>>> j
‘.*\\.txt\\,\\ c[eao].*\\.txt\\,\\ t.\\.csv\\Z(?ms)’
>>>

We can get the original regex (for reusing later).

glob Module in Python

glob Module in Python

Thanks to glob module, we can use wildcards with Python in finding pathnames.

>>> import glob
>>> dir(glob)
[‘__all__’, ‘__builtins__’, ‘__cached__’, ‘__doc__’, ‘__file__’, ‘__initializing
__’, ‘__loader__’, ‘__name__’, ‘__package__’, ‘fnmatch’, ‘glob’, ‘glob0’, ‘glob1
‘, ‘has_magic’, ‘iglob’, ‘magic_check’, ‘magic_check_bytes’, ‘os’, ‘re’]
>>>

You can see that glob module contains other modules: os, re, and fnmatch. So it’s a very powerful.

Let’s see the functions:

glob

>>> glob.glob(“D:/”)
[‘D:/’]
>>> for f in glob.glob(“*.txt”):
…     print(f)

ert.txt
et.txt
LICENSE.txt
NEWS.txt
README.txt
>>>

>>> for f in glob.glob(“D:/*.txt”):
…     print(f)

D:/artyk.txt
D:/derek.txt
D:/dereka.txt
D:/pliczek.txt
>>>

>>> for f in glob.glob(“D:/*.*”):
…     print(f)

D:/ale.csv
D:/artyk.txt
D:/cs14.cs
D:/derek.txt
D:/dereka.txt
D:/Photo0045.jpg
D:/Photo0046.jpg
D:/Photo0047.jpg
D:/Photo0048.jpg
D:/Photo0058.jpg
D:/pliczek.txt
D:/processlist.csv
D:/processlist.html
D:/processlist.xml
>>>

>>> f = glob.glob(“D:/*.*”)
>>> print(f)

>>> print(f)
[‘D:/408998_10151307870152631_1487917839_n.jpg’, ‘D:/970107_449345235148911_6212
97987_n.jpg’, …, ‘D:/zeta.csv’]
>>>

Glob is used to get a list of items.

iglob

>>> f = glob.iglob(“D:/*.*”)
>>> print(f)
<generator object iglob at 0x00C7B490>
>>> for g in f:
…     print(g)

D:/408998_10151307870152631_1487917839_n.jpg
D:/970107_449345235148911_621297987_n.jpg
D:/ale.csv
D:/artyk.txt
D:/cbsidlm-cbsi5_4_0_104-Advanced_SystemCare-BP-10407614.exe
D:/derek.txt
D:/dereka.txt
D:/eta.csv
D:/Photo0045.jpg
D:/Photo0046.jpg
D:/Photo0047.jpg
D:/Photo0048.jpg
D:/Photo0058.jpg
D:/processlist.csv
D:/processlist.html
D:/processlist.xml
D:/zeta.csv
>>>

>>> list(glob.iglob(“D:/*.txt”))
[‘D:/artyk.txt’, ‘D:/derek.txt’, ‘D:/dereka.txt’, ‘D:/pliczek.txt’]
>>>

So iglob is used to get an generator.

>>> f = glob.iglob(“D:/*.txt”)
>>> f
<generator object iglob at 0x00C7EC38>

We can get an item from our generator one by one:

>>> f.__next__
<method-wrapper ‘__next__’ of generator object at 0x00C7EC38>
>>> f.__next__()
‘D:/artyk.txt’
>>> f.__next__()
‘D:/derek.txt’
>>> f.__next__()
‘D:/dereka.txt’
>>>

Exceptions in Python

Exceptions in Python

We can raise an exception very easy:

>>> f = 6
>>> if f  == 6:
…     raise RuntimeError(“Nie mogę kontynuować, bo f jest równe 6”)

Traceback (most recent call last):
  File “<stdin>”, line 2, in <module>
RuntimeError: Nie mogę kontynuować, bo f jest równe 6
>>>

We can create our own exception type. First, we define the class for our exception:

>>> class FException(RuntimeError):
…     pass

Then, we can try it:

>>> f = 6
>>> if f == 6:
…     raise FException(“Nie mogę kontynuować, bo f jest równe 6”)

Traceback (most recent call last):
  File “<stdin>”, line 2, in <module>
__main__.FException: Nie mogę kontynuować, bo f jest równe 6
>>>

It works! Let’s see other value for f:

>>> f = 80
>>> if f == 6:
…     raise FException(“Nie mogę kontynuować, bo f jest równe 6”)

>>>

There’s no exception. Yes, that’s it. However, we can extend this exception system in Python.

try:

the program code

except:

the code that will be executed when there will be an error

else:

the code will be executed when there won’t any error

We can catch and handle an exception if we know our code can do that. An easy way to show how Exceptions in Python work:

>>> try:
…     t = open(“ert.txt”, “w”)
…     t.write(“My”)
except IOError:
…     print(“Błąd!”)
else:
…     print(“Sukces!”)

2
Sukces!
>>> t.close()

And…
>>> try:
…     t = open(“ert.txt”, “r”)
…     t.readline()
except IOError:
…     print(“Błąd!”)
else:
…     print(“Sukces!”)

‘My’
Sukces!
>>> t.close()

The program is running without any errors, but the code is secured if need be. So let’s try to make an error:

>>> try:
     t = open(“eka.txt”, “r”)
…     t.readline()
except IOError:
…     print(“Błąd!”)
else:
     print(“Sukces!”)

Błąd!
>>>

For people who don’t speak in Polish, I should explain that “Błąd” is “Error” in English.

try:

the program code

finally:

the code will be executed when there won’t any error or be an error

if there’s any error, it won’t appear, and the program will go to the instruction after finally:

>>> try:
…     t = open(“et.txt”, “w”)
…     t.write(“Olo”)
… finally:
…     t.close()

3
>>>

Great, everything has been successful.

>>> try:
…     t = open(“ert.txt”, “r”)
…     u = t.readline()
… finally:
…     t.close()

And again:

>>> try:
…     t = open(“ert.txt”, “r”)
…     u = t.readline()
…     print(u)
… finally:
…     t.close()

Olo

But…
>>> try:
…     t = open(“eu.txt”, “r”)
…     u = t.readline()
… finally:
…     t.close()

Traceback (most recent call last):
  File “<stdin>”, line 2, in <module>
FileNotFoundError: [Errno 2] No such file or directory: ‘et.txt’
>>>