– iteration: -! specific no of times: range(5) -! as long as the variable : for ch in “Hello” – querying the directory of the module for objects to use: e.g. import random dir(random) – asking for help with the object we searched: help(random.randint) – sleep function: import time time.sleep(5) – Know that everything is an object in python – Built in data structures: list, dictionary, tuple and sets -! lists are dynamic and mutable too. -! methods: append() , len(list_name), remove(item_name),pop(index),pop()-last element removed -! methods: extend([3,4]),insert(index,item),pop() returns the removed value -! copying using assignment is not actual. it just points to the same thing. first = [1,2,4] second = first first.append(5)

-! checking membership with "in" and "not in"
-! method: list[start:stop:step] to make a new list out of old one.
-!''.join(list[::2]) makes a string out of list elements.

-! tuples are immutable: can’t be changed in runtime -! () -! t = (‘Python’) is a string but t=(‘Python’,) is a tuple -! -! dictionaries are unordered set of key and value pairs. -! dictionary of dictionaries is a table. -! sorted(dict_name) -! .setdefault(key, value) -! for letter in vowels: found.setdefault(letter,0)

-! set are unordered and set of unique objects. -! {} -! union method combines one set with another e.g vowels.union(set(word)) -! .difference(set2) gives the A-B in set notation. -! similarly .intersection -! can replace several iters of search and for loops to iterate through dictionaries and lists.

– what a nice way to print: print(’\t’*2,char) – if print looks messy, #use pprint pretty print e.g import pprint pprint.pprint(Anything) – functions and methods into a single file used for reuse: module -! """ This is documentation string for function""" -! return bool(result) : True or False -! empty set is represented as set() by the interpreter -! function annotations are optioinal and informational e.g def search4vowel(word:str) -> set: This means it expects the argument to be a string and returns a set. -! using help will show us docstring as well as it’s expected input and output. -! passing default arguments with assignment operator -! not only positional assignment is possible but keyword assignment can be done. e.g the 1st arg can be written second or anywhere if keyword is specified. – Making a module: -! default search locations:

  1. cwd
  2. interpreter’s site packages locations
  3. standard library locations

-! easiest use : make a folder mymodules in cwd and using it go to the folder and import statement can be used. -! can’t use import /mymodules/vsearch -! but no worries: we can get the module into site packages using setuptools:

  1. create a distribution description -! create at least two files: README.txt and setup.py e.g of setup.py from setuptools import setup setup( name=‘vsearch’, version=‘1.0’, description=‘The first vowel search module’, author=‘Alok Regmi’, author_email=‘[email protected]’, url=‘alokregmi.com.np’, py_modules=[‘vsearch’], ) the readme file needs to be built but doesn’t need to contain anything at all.

  2. Generate a distribution file -! C:\Users\mymodules> py -3 setup.py sdist in Windows results in a zip file i.e installable file. -! on unix like os mymodules$ python3 setup.py sdist

  3. Install the distribution file -! using pip now you can install the packages -! On windows : py -3 -m pip install vsearch-1.0.zip -! on unix: python3 -m pip install vsearch-1.0.tar.gz

– Pass by object reference is by default in python: e.g double(num) gives twice the num but doesn’t change the value of num. but a function where list is passed and appended inside it will have the element permanently. – if passed argument allows mutability, the arg passed is pass by reference. so lists, dictionaries and sets are passed into a function by reference. strings,integers and tuples being immutable are passed into a function by value. – Strangest phenomenon of all: e.g def double(arg): arg = arg * 2 def change(arg): arg.append(“More data”) If we pass a list as arg, it’s not changed out in first function ie. double(list_arg) but it is changed in 2nd function i.e change(list_arg) Reason: The first function has assignment so right of assignment is calculated. so it’s a list with twice the elements. so the value created has it’s object reference assigned to the variable symbol on the left of = symbol. so this code creates a new value, and is assigned a new object reference and this reference is assigned to the arg variable. so it overwrites the previous object reference in arg. However, the old object reference still exists in the calling code and it’s value hasn’t changed, so the shell sees the original list not the one created in the function. The second one calls a method to the same list and same reference so changes the content of the list. – meeting the standards and compliances: -! install the pytest module and pep8 plugin. i.e pytest, pytest-pep8 -! py.test –pep8 vsearch.py

– Building a webapp using Flask: -! simplest web server in flask: from flask import Flask #this is the class name Flask with uppercase F app=Flask(name) # it creates tn object of type Flask and assigns to app variable

@app.route(’/’ # decorating a function with a url

def hello() -> str: return ‘Hello in the world of Flask’

app.run()

-! Building the HTML form to code the function into the web page: -! powered by jinja2 engine -! {{ }} template directive : indicates value will be provided prior to rendering i.e. argument to a template -! {% %} substitute the block of html prior to rendering and is provided by any page that inherits from it. -! rendering template: @app.route(’/entry’) def entry_page() -> ‘html’: return render_template(’entry.html’, the_title=‘Welcome to search4letters web’) -! handling post data to a decorator: @app.route(’/search4’, methods=[‘POST’]) now the search4 url supports post method -! debugging mode: app.run(debug=True) -! using the request data in webapp: from flask import request @app.route(’/search4’…) def do_search() -> str: phrase = request.form[‘phrase’] letters = request.form[’letters’] # this variable in sq brackets need to be defined in html form code. title = ‘Here are results’ results = str(search4letters(phrase,letters)) return render_template(‘results.html’, the_phrase=phrase, the_letters=letters, the_title=title, the_results=results,)

-! redirect to avoid unwanted errors: @app.route(’/’) def hello() -> ‘302’: return redirect(’/entry’) # annotate to clearly indicate that HTTP status code is returned .

-! @app.route(’/’) @app.route(’/entry’) def do_search()-> ‘html’: ….

– dunder: if name == ‘main’:

– Working with files: open, process and close -! todos = open(’todos.txt’, ‘a’) print(‘Put on the trash’, file=todos) # printing to filestream todos.close() -! tasks = open(’todos.txt’) for chore in tasks: print(chore, end=’’) # there is already a new line in file so it removes the extra new line in between. tasks.close() -! modes: r, w , a , x where if file previously exists it fails, xb or x+b -! easier opening, processing and closing of a file: use with statement with open(’todos.txt’) as tasks: for chore in tasks: print(chore, end=’’) -! printing the data in html with all andgle brackets and so on: escape(‘This is a ’) from flask import escape

Pg 257

-! the request file is boring so we do: str(dir(request)) # dir produces a list then we stringify that list and save to the log file. doing dir we see a lot of methods to work on request. but we don’t need this info into the log file. so we use request.form request.remote_addr request.user_agent -! using vertical bars as delimiiters: print(req.form, file=log, end=’|’) print(req.remote_addr, file=log, end=’|’) print(res,file=log)

-! these lines above can be written into one line as: print(req.form,req.remote_addr, res,file=log,sep=’|’)

-! after use of delimiter we can convert it into list using .split(’|’)

  1. first read a line: with open(‘vsearch.log’) as log: contents = log.readlines() return escape(’’.join(contents))
  2. then use the contents and read it using split(’|’) method.
  3. then you get a list of lists.
  4. parse it using the proper html tag. , and so on.

– Working with db-api:

  1. install mysql server
  2. install mysql python driver
  3. create webapp’s database and tables.

– Classes and abstraction: -! pass a valid statement that does nothing -! naming convention: functions: lowercase e.g. count_from_by() classes: Camelcase e.g. CountFromBy() -! Objects share behavior but not state. i.e methods but not variables -! the methods in python always take one argument i.e the object itself. e.g c.increase() is same as CountFromBy.increase(c) where c is an object of the class CountFromBy -! def increase(self): is the default way. -! the variables are used with self.sth because the variables need to be in the scope of the current object. -! there are several dunders which can be overridden to our purpose such as: ge for greater than sign with objects eq for == operator usage init for initialization of the attributes related to the object -! __repr__(self) -> str: return str(self.name)

– Now dancing with the decorators:

– Reading csv: import csv with open(‘buzzers.csv’) as data: for line in csv.reader(data): print(line) -! this also can be done with csv.DictReader which stores as dict.

– Converting patterns to comprehensions: destinations = [] for dest in flight.values(): destinations.append(dest.title())

more_dests = [ for dest in flights.values()]

more_dests = [dest.title() for dest in flights.values()]

-! comprehensions are not just for lists but for dicts as well. flights2={} for k,v in flights.items(): flights2[convertam2pm(k)] = v.title() #lets succintize this: more_flights = {for k,v in flights.items()} # the iteration part first #need to add the functionality now more_flights = {convert2ampm(k):v.title() for k,v in flights.items()} #the key value pair is specified first and then processed.

-! now extending comprehensions with filters: if context is like: iterate, filter, then make a new dict e.g. just_freeport = {} for k, v in flights.items(): if v == ‘FREEPORT’: just_freeport[convert2ampm(k)] = v.title()

just_freeport2 = {convert2ampm(k): v.title() for k, v in flights.items() if v == ‘FREEPORT’}

-! comprehensions spanning multiple lines: just_freeport3 = {convert2ampm(k): v.title() for k, v in flights.items() if v == ‘FREEPORT’}

-! when2 = {dest: [k for k, v in fts.items() if v == dest] for dest in set(fts.values())} #it’s making a list out of the set of places, compares it and iterates into a list as well.

-! the next big things: generators -! When you replace your listcomp’s square brackets with parentheses, the listcomp becomes a generator, and your code behaves differently. -! list comprehension waits for all data to be produced but generator releases as soon as one’s available.

-! Decorators usage:

  1. Output formatting
  2. Authentication BoilerPlate