Black Mamba

Faster, Higher, Stronger.

Python Notes I

Work effectively with IDLE

  • Press TAB key, IDLE will offer suggestions to help you complete your statement
  • Press Alt-P to recall the previous code statement and press Alt-N to move to the next code statement

Deal with Python list

  • Python’s variable identifiers don’t have a type, Python’s list is a high-level collection
  • Using print() and len() to work out how many data items are in the list
1
2
3
4
5
6
7
animal  = ["Dog", 'Pig', 'Cat', "Duck"]
print(animal)
['Dog', 'Pig', 'Cat', 'Duck']
print(len(animal))
4
print(animal[1])
Pig
  • Using append(), extend() and pop() method to add and remove data from the list
1
2
3
4
5
6
7
8
9
10
animal.append("Tiger")
print(animal)
['Dog', 'Pig', 'Cat', 'Duck', 'Tiger']
animal.pop()
'Tiger'
print(animal)
['Dog', 'Pig', 'Cat', 'Duck']
animal.extend(["Fish", "Bird"])
print(animal)
['Dog', 'Pig', 'Cat', 'Duck', 'Fish', 'Bird']
  • Using remove() and insert() to find and remove or add a specific data from list
1
2
3
4
5
6
animal.remove("Pig")
print(animal)
['Dog', 'Cat', 'Duck', 'Fish', 'Bird']
animal.insert(1, "Bull")
print(animal)
['Dog', 'Bull', 'Cat', 'Duck', 'Fish', 'Bird']
  • For loops work with lists of any size
1
2
3
animals = ["Dog", 'Pig', 'Cat', "Duck", "Fish"]
for each_animal in animals:
    print each_animal
  • Store list within lists
1
2
3
4
5
6
7
8
9
10
11
12
movie = ["Titanic", 1997, "Romance & Disaster", "194 minutes", ["James Cameron", ["Leonardo DiCaprio", "Kate Winslet", "Billy Zane", "Kathy Bates", "Frances Fisher"]]]
for each_item in movie:
    print each_item

Titanic
1997
Romance & Disaster
194 minutes
['James Cameron', ['Leonardo DiCaprio', 'Kate Winslet', 'Billy Zane', 'Kathy Bates', 'Frances Fisher']]

print movie[4][1][0]
Leonardo DiCaprio

Don’t repeat code and create a function

  • isinstance() BIF checks whether an identifier refers to a data object of some specified type
  • Using def to define a custom function
1
2
def function_name (arguments):
    code suite
  • Python3 defaults its recursion limit to 1,000
  • Print items in list within lists
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
def print_item(the_list):
    for each_item in the_list:
        if isinstance(each_item, list):
            print_item(each_item)
        else:
            print(each_item)

print_item(movie)

Titanic
1997
Romance & Disaster
194 minutes
James Cameron
Leonardo DiCaprio
Kate Winslet
Billy Zane
Kathy Bates
Frances Fisher

Build a distribution and upload code to PyPI

  • Create a folder for the module
  • Create a file called “setup.py” in the new folder
1
2
3
4
5
6
7
8
9
10
11
from distutils.core import setup

setup(
    name = 'nester',
    version = '1.0',
    py_modules = ['nester'],
    author = 'name',
    author_email = 'name@somewhere.com',
    url = 'name@someplace.com',
    description = 'A simple printer of nested lists',
    )
  • Build a distribution file, enter the command at the prompt
1
python3 setup.py sdist
  • Install the distribution into local copy of Python
1
python3 setup.py install
  • Then, the module has been transformed into a distribution and installed into local copy of Python
1
2
# at the first time, should type the username and password
python3 setup.py register
  • Finally, upload code to PyPI
1
python3 setup.py sdist upload

Import a module to use it

  • For instance, there is a function named “nester.py”
1
2
3
4
5
6
7
def print_item (the_list):
    # This function takes a argument called "the_list"
    for each_item in the_list:
        if isinstance(each_item, list):
            print_item (each_item)
        else:
            print (each_item)
  • Type F5 to run the module’s code, use the following list data
1
2
3
4
5
# allow us to access nester's functions
import nester
animals = ['Pig', 'Dog', 'Cat', 'Bird', 'Fish']
# "nester" is associated namespace which like family names helps to qualify what the code mean
nester.print_item(animals)

Use optional arguments

  • Update the function “nester.py” with default arguments
1
2
3
4
5
6
7
8
9
def print_item (the_list, indent=False, level=0):
    for each_item in the_list:
        if isinstance(each_item, list):
            print_item (each_item, indent, level+1)
        else:
            if indent:
                for tab_stop in range(level):
                    print("\t", end='@!')
            print (each_item)
  • Use indent to control whether indent code
  • Use level to control the init indentation level

Update reversion to PyPI

  • Edit “setup.py” so that it has a new version
1
version = '1.1',
  • Upload the new distribution to PyPI
1
python3 setup.py sdisk upload

Bonus I: Python BIFs

  • BIFs is short for build-in functions, it can mean less code to write
  • There were over 70 BIFs in Python3
  • BIFs have their very own namespace called builtins
  • At Python or IDLE shell, typing dir( builtins ) to see a list of the built-in functions
  • To find out what any BIF does—like input(), for example—type help(input) at the shell for a description of the BIFs function
  • Before write new code, think BIF at first

Bonus II: .pyc Files

  • If the module code hasn’t changed, no translation occurs and the “compiled” code is executed
  • If the code has changed, the translation occurs (creating a new .pyc file) as needed
  • When Python sees a .pyc file, it tries to use it because doing so makes everything go much faster
  • The use of .pyc file (if found) is primarily a potential runtime optimization performed by the interpreter, it can’t be created by users

Comments