[IN CONSTRUCTION] Notes: Python: Part 2: Modularity

[THIS POST IS IN CONSTRUCTION]

In my spare time, I will be learning about Machine Learning, Artificial Intelligence, Data Science and other topics where Python is the interpreted language of choice.
Below are some fast notes I cleaned up to share to however is interested. Disclaimer: I am not responsible of the content or how you use the content. The responsibility fall on you.

We can import modules using the import keyword.

Note: Remember to use 4 spaces for indentation and use UTF-8 encoding with your editor when saving py files.

Functions

Fetch words. Assume this is in the words.py file:

from urllib.request import urlopen

def fetchWordsFromUrl(url): 
    with urlopen(url) as content:
        words = []
        for each_line in content:
            array = each_line.split()
            for each_word in array:
                words.append(each_word)
        return words

Using words.py file with python:

>>> import words
>>> words.fetchWordsFromUrl('https://wordpress.org/plugins/about/readme.txt')

Running as Script or Repo

import sys
from urllib.request import urlopen

def fetchWordsFromUrl(url): 
    with urlopen(url) as content:
        words = []
        for each_line in content:
            array = each_line.split()
            for each_word in array:
                words.append(each_word)
        return words

if __name__ == '__main__'
    fetchWordsFromUrl(sys.argv[1])

 

Other Functions

Bytes to Int 32:

def _bytes_to_int32(b):
    return b[0] |
              b([1] << 8) |
              b([2] << 16) |
              b([3] << 24)

Int 32 to Bytes:

def _int32_to_bytes(i):
    return bytes( (i & 0xff,
                         i >> 8 & 0xff,
                         i >> 16 & 0xff,
                         i >> 24 & 0xff) )

Even or Odd:

def isEvenOrOdd(n):
    return n % 2 == 0

Square:

def square(n):
    return n * n

Note: Code Execution.  

$ python3 code.py 99

 

Share
Leave a comment

Notes: Python: Part 1

In my spare time, I will be learning about Machine Learning, Artificial Intelligence, Data Science and other topics where Python is the interpreted language of choice.
Below are some fast notes I cleaned up to share to however is interested. Disclaimer: I am not responsible of the content or how you use the content. The responsibility fall on you.

Exiting REPL: Ctrl-Z (Windows), Ctrl-D (Linux, OSX)

The Zen of Python, by Tim Peters: https://www.python.org/dev/peps/pep-0020/

Import

Here are some example of import plus a code so you can get a general idea of how thing are going to look:

>>> import math
>>> from urllib.request import urlopen
>>> with urlopen('https://wordpress.org/plugins/about/readme.txt') as content:
...        words = []
...        for each_line in content:
...            array = each_line.split()
...            for each_word in array:
...               words.append(each_word)
...
>>> 

 

Each element in the words array, is a byte therefore it will be in [b’word’, b’another’…] format; therefore, we can decode the bytes into strings:

>>> import math
>>> from urllib.request import urlopen
>>> with urlopen('https://wordpress.org/plugins/about/readme.txt') as content:
...        words = []
...        for each_line in content:
...            array = each_line.decode('utf-8').split()
...            for each_word in array:
...               words.append(each_word)
...
>>> 

 

“//” Integer division:

>>> import math
>>> n=5
>>> n=3
>>> fac(n) / (fac(k) * fac(n-k))
10.0
>> fac(n) // (fac(k) * fac(n-k))
10

(*) You can use math.factorial(n) if you don’t import. Using fac is the short of factorial.

The limit of results are not based on the type of variable but based on the limit of memory so a huge factorial such as factorial(13) it would give us a result without troubles.

 

Number of Characters. Example:

>>> len(str(fact(n)))

 

“**” Exponential:

 

>>> 2**31 – 1
2147483647

 

Scalar Type and Type Conversions:

 

>>> 10
10
>>> 0b10     # base 2
2
>>> 0o10    # base 8
8
>>> 0x10    #base 16
16
>>> int(3.5)  
3
>>> int(“500”)
500
>>> int(“10000”, 3)     # 0, 1, 2 of base 3?
81
>>> 3e8
300000000.0
>>> float(8)
8.0
>>> float(“nan”)
Nan
>>> Float(“-inf”)
-inf
>>> 2.0 + 1
3.0
>>> a = None
>>> a is None
True
>>> True
True
>>> bool(0)
False
>>> bool(99)
True
>>> bool(0.0)
False
>>> bool (0.2)
True
>>> bool(-1.1)
True
>>> bool([])              # [] Empty Array
False
>>> bool([1, 2, 3])
True
>>> bool(“”)
False
>>> bool(“Hello”)
True
>>> bool(“False”)    #You cannot convert from String to Boolean in this way
True

Float Type: IEEE-754 double precision (64-bit). 53 bits of binary precision. 15 to 16 bits of decimal precision.

None: Value of NoneType which is used to represent the absence of a value.

 

Conditional Statement

The expression, expr, is converted to bool as if by the bool() constructor

Note: Remember to indent 4 spaces

 

>>> if True
…       print(“Hello World!”)
Hello World!
>>> if bool(“eggs”):
…       print(“2 please”);
2 Please
>>> if “eggs”:
…        print(“3 please”)
3 please
>>> n = 10
>>> if n > 20:
…       print(“Yes”)
…    else:
…       print(“No”)
No
>>> if n > 20:
…       print(“Yes”)
…    elseif n == 10:
…       print(“Same”)
…    else:
…       print(“No”)
Same

If you are planning to do nested if statement, perhaps you considered to use “elif” instead of “else: [return + 4 spaces] if”

Reminder: Flat is better than nested

 

Loops:

White loop:

>>> n = 2
>>> while n != 0:
…         print (n)
…         n -= 1
2
1
>>> n = 2
>>> while n:  # While there is a number is true, when reaching 0 is false. Previous form is preferred
…        print(n)
…        n -= 1
2
1
>>> while True:
…         response = input()
…         if int(response) % 10 == 0:
…              break
…
13
67
100
>>>

Exiting Loop: Pressing Ctrl+C which is an exception

Keyword “break”: Terminates the innermost loop. Transferring execution to the first statement after the loop.

 

For Loops:

 

>>> names = [“Alejandro”, “Diego”, “Dado”]
>>> for name in names:
…         print(name)
…
Alejandro
Diego
Dado
>>> colors = { ‘red’: ‘0xFF0000’, ‘blue’:’0x0000FF’, ‘green’:’0x00FF00’}
>>> for color in colors:
…        print (color, colors[color])
…
red 16711680
blue 255
green 65280
>>> 

Strings

Str: Immutable sequence of Unicode code-points. Once you construct cannot be modified

Since quotes (‘) and double-quotes (“) are allowed but must be consistence

 

>>> “One” “Two”
‘OneTwo’

Note: Practicality beats purity “Beautiful text strings. Rendered in literal form. Simple elegance.”

String with New Lines:

  • Option 1: Multilines strings using triple double-quotes or triple single quotes (like in grails)

 

>>> “”” This is
…    a multiline string.
…    Deal with it!”””
‘This is\na multiline string\nDeal with it!’
>>> ‘’’ This is
…    a multiline string.
…    Deal with it!’’’
‘This is\na multiline string\nDeal with it!’

 

  • Option 2: Escape sequences
>>> m = ‘This is\na multiline string\nDeal with it!’
>>> m
‘This is\na multiline string\nDeal with it!’
>>> print(m)   #Print what are we representing
This is
a multiline string
Deal with it!
>>>

 

Note: Python has Universal Newlines which means you only need to use ‘\n’ and not worry of do ‘\r\n’ for windows or ‘\n’ for linux/osX. For more information: http://www.python.org/dev/peps/pep-0278/

Escape Strings:

>>> “This is a \”text\””
‘This is a “ text“’
>>> ‘This is a \’text\’’
“This is a ‘text’”
>>> ‘This is a \” crazy \’ text’
‘This is a “ crazy \’ text’
>>> s = “A \\ in the string to use”
>>> s
‘A \\ in the string to use’
>>> print (s)
A \ in the string to use
>>>

Note: More information about Escape string in http://docs.python.org/3/reference/lexical_analysis.html#Strings

 

Dealing with Windows Double BackSlashes using Raw Strings:

>>> file_path = r’C:\Windows\text.rft’
>>> file_path
‘C:\\Windows\\text.rft’
>>> print (file_path)
C:\Windows\text.rft
>>>

 

Create Strings from Other Types:

 

>>> str(500)
‘500’
>>> str(7.03e23)
‘7.03e+23’

 

String Common Operations

 

>>> s = “Alejandro”
>>> s[3]
‘j’
>>> type(s[3])
<class ‘str’>
>>> c = “alex”
>>> c.capitalize()
‘Alex’
>>> c
‘alex’

Note: There is no separate character type. The “characters” are simply one element strings.

Note: Use help for more information.

International Use: Python strings are Unicode. Default encoding is UTF-8 literals. Using ‘\u00e5’ for example, you can print the letter å. Also you can use ‘\xe5’ and ‘\345’ to get the same character.

 

Bytes

They are immutable sequence of bytes.

Byte literals: Prefix by letter b

b’data’

b”data”

Note: They support almost most operations of string

 

>>> d = b’One Two Bytes’
>>> d.split()
[b’One’, b’Two’, b’Bytes’]
>>> 

 

Converting Between Strings and Bytes:

Str => encode => bytes

Bytes => decode => Str

Bytes support a long range of encodings: http://docs.python.org/3/library/codecs.html#standard-encodings

 

>>> text = “å fotære”
>>> data = text.encode(“utf-8”)
>>> data
\xc3\xa5 fort\xc3\xa6re
>>> text2 = data.decode(“utf-8”)
>>> text2
å fotære
>>> text == text2
True
>>> 

(*) å is \xc3\xa5 and æ is \xc3\xa6

Note: Important to understand since information is transmitted in byte streams when dealing with files, network resources, and HTTP responses.

List

They are mutable sequences of objects

[a, b, c, d]

 

>>> [1, 2, 3]
[1, 2, 3]
>>> a = [“Alejandro”, “Godofredo”, “Carlstein]
>>> a[1]
‘Godofredo’
>>> a[1] = 10
>>> a
[‘Alejandro’, 10, ‘Carlstein’]
>>> b = []
>>> b.append(2.1)
>>> b.append(3.0)
>>> b
[2.1, 3.0]
>>> list (“Alex”)
[‘A’, ‘l’, ‘e’, ‘x’]
>>> c = [‘A’,
…            ‘b’,
…            ‘c’,] #We are allowed to add a coma and it would not create an issue

 

Dictionaries

Dict: Mutable mappings of keys to values

{key1 : value1, key2 : value2}

 

>>> m = { ‘firstname’ : ‘Alejandro, ‘lastname’ : ‘Carlstein’}
>>> m[‘firstname’]
‘Alejandro’
>>> m[‘firstname’] = ‘Godofredo’
>>> m
{ ‘firstname’ : ‘Godofredo, ‘lastname’ : ‘Carlstein’}
>>> m[‘middlename’] = ‘Alex’
>>> m
{ ‘firstname’ : ‘Godofredo, ‘lastname’ : ‘Carlstein’, ‘middlename’ : ‘Alex’}
>>> empty_map = {}

 

 

 

 

Share
Leave a comment