29.    Python and its Developing Approaches

December 18, 2018
home

Contents

01. Python First Look, Nov.30, 2018


            section 4: Python syntax, you can see the semicolor, and indentation.
                if 5 > 2 :
                    print("Five is greater than two!")
            section 10: Python Lists, the main data structure
                thislist = ["apple", "banana", "cherry"]
                print(thislist)
            section 11: Python tuples, not mutable
                thistuple = ("apple", "banana", "cherry")
                print(thistuple)
            
            note: If you get the result set from a database table
                  - It is a list with many tuple elements.
                  - Python language itself does not have type data frame.
                  - But, its package pandas has type dataframe.
                  - Package pandas also provides functions to manipulate a dataframe.
                  - Package pandas also provides data virtualizations(ploting graphics) like R langauge environment.
                  - This demonstrates that Python can do some special tasks.
            
            

02. test in Python Command Line

03. test a Python file

04. test in a IDE, code visual studio, MAC

        the folder structure as below:

                    folder: lab_subdir
                        folder: mydir
                            file:  myMath.py
                    file: main.py
            

04x. Using Standard module, code visual studio, MAC

            1. create a root folder, lab_standard_module
            2. under it, create a text file.
            3. under it, create main.py as below:
                
                import os

                if os.path.exists("demofile.txt"):
                    print("It exist.")
                else:
                    print("It does not exist.")

                print("os is " + str(type(os)))
                print("os.path is " + str(type(os.path)))  
                
            4. run it
            5. The result is as below:
                It exists.
                os is  'module'
                ps.path is 'dictionary'
            
            os is a standard module. When python3 is installed, it is part 
            of python installation. There is no need to download when using it.
            

            This demo references w3c python tutorial, file handling.
            

05. Develop on the Web

05x. demo-1, develop on the Web

        1. create a root folder, lab_1_web
        2. open code visual studio, open the above folder
        2. under it, create a python file main.py 
        3. under it, crete a subfolder, mydir
        4. under lab_1_web/mydir, create camelcase_lab.py
            
        -----   camelcase_lab.py
        import camelcase

        c = camelcase.CamelCase()
        txt = "merry christmas"
        print(c.hump(txt))

        print("camelcase is " + str(camelcase))
        print("c is " + str(c))   
           
       
        5. no test in code visual studio

        6. Following topic 05, open a browser
        7. navigate to  https://repl.it/site/languages/python3 
        8. upload the folder mydircreated in step 1-4
        9. main.py, code as below
        
         -----   main.py   ----------------------
        #rom mydir import x
        from mydir import camelcase_lab
        #rom mydir import y
        #rom mydir import z
        

        10. on the left, click package icon,
            enter camelcase
            select it
        
        11. run it.
        12. You see
                merry christmas  => Merry Christmas
                camelcase is a module
                c is an object.        
        

05y. demo-2, develop on the Web - MySql

        # mysql_peter.py
        import mysql.connector

        mydb = mysql.connector.connect(
          host="xxxx.winhost.com",
          user="xxxxxxxx",
          password="xxxxxxxx",
          database="mysql_56314_peter"
        )
        print(mydb)

        mycursor = mydb.cursor()
        mycursor.execute("SELECT * FROM dogs")
        myresult = mycursor.fetchall()

        for x in myresult:
          print(x)

        print(type(myresult))     # list
        #('Tairo', 'brown')       tuple
        #('emi'), 'white')....    tuple

        print("after mysql test 4")
            

06. w3c_python_mongodb

        import pymongo

        myclient = pymongo.MongoClient("mongodb://xyz/")
        mydb = myclient["mydatabase"]
        mycol = mydb["customers"]

        myquery = { "address": "Park Lane 38" }

        mydoc = mycol.find(myquery)

        for x in mydoc:
          print(x)
            

07. create a web server from python language, oo feature

        from http.server import HTTPServer, BaseHTTPRequestHandler
        print("location 1, test 3")

        class Serv(BaseHTTPRequestHandler):
            def do_GET(self):
                if self.path == '/':
                    self.path = '/index.html'
                try:
                    file_to_open = open(self.path[1:]).read()
                    self.send_response(200)
                except:
                    file_to_open = "File not found"
                    self.send_response(404)
                self.end_headers()
                self.wfile.write(bytes(file_to_open, 'utf-8'))

        print("location 2")

        httpd = HTTPServer(('localhost', 8080), Serv)
        httpd.serve_forever()
            

08. notes from learning w3c python tutorial

01. python casting

            # using constructor functions for casting
            # examples as below
            y = int(2.8)      # y will be 2
            w = float("4.2")  # w will be 4.2
            z = str(3.0)      # z will be '3.0'
            # in python single quote and double quotes are the same for a string.
            

02. python data structure

name assignment constructor features
List l = ["apple", "banana", "cherry"] l = list(("apple", "banana", "cherry")) mutable
Tuple t = ("apple", "banana", "cherry") t = tuple(("apple", "banana", "cherry")) not mutable
Set s = {"apple", "banana", "cherry"} s = set(("apple", "banana", "cherry")) unique contents
Dictionary d = {"brand": "x","model": "y"} d = dict(brand="x", model="y") key-value pair

03. Python if-elif-else

ref: my topic 30 - 05

04. Semi Colon

05. Lambda Function

        #------------    lab 1:   lambda function definition   -------------------
        x = lambda a, b, c : a + b + c
        print(x(5, 6, 2))                   # 13
        print("x is " + str(type(x)))       # x is a function
            
  • lambda a, b, c : a + b + c is a lambda fucntion
  • a small anonymous function
  • It can take any number of arguments, like a, b, c, but can only have one expression to return like a + b + c
        #------------    lab 2:   A function using a lambda function   -----------------
        def myfunc(n):                  # myfunc is a function
          return lambda a : a * n       # lambda a : a * n  is a function

        mydoubler = myfunc(2)           # mydoubler is a fimction

        print(mydoubler(11))
            
  • argument 2 is for the lambda function
  • argument 11 is for the outside function.

06. Object Oriented

    
    class Person:         # declare a class  

    #self is needed within the class definition. 
    def __init__(self, name, age):   # used when instantiating an object
        self.name = name
        self.age = age

      def myfunc(self):
        print("Hello my name is " + self.name)

    
    p1 = Person("John", 36)     # instantiate an object

    print(Person)        # class _ _ main_ _.Person
    print(p1)            # _ _ main_ _.Person object at 0x10fe..fo
    print(p1.name)       # property
    p1.myfunc()          # method
        
    notes
  • ALL classes have a function called __init__(), which is always executed when the class is being initiated.
  • Unlike other oo languages, no access scope keywords - public, private...

07.    Module

  • create a folder, w3c_22_module
  • under it, create 3 files as below:
        # ---  mymodule.py ---------------
        def greeting(name):
          print("Hello, " + name)

        person1 = {
          "name": "John",
          "age": 36,
          "country": "Norway"
        }

        # --- test1.py     ------------------
        import mymodule as mm
        mm.person1["age"])               # 36
        print(mm.greeting("Mary"))       # Hello, Mary

        # --- test2.py     ------------------
        from mymodule import person1
        from mymodule import greeting

        print(person1["age"])      # Use the dictionary data directly.
        greeting("Mary")           # Use the function directly.

        
    mymodule.py
  • a python file
  • a python module
  • It has two elements - a function and a diectionary object.
    test1.py
  • use mymodule.py
  • First, import the module without file extension, making it accessible.
  • Then, call the function, and use the object(dictionary) data
    test2.py
  • use mymodule.py
  • use keyword from

07x.    Built-in Module

  • There are several built-in modules in Python, which you can import whenever you like.
  • One example is as below:
  • Key word import is needed. It consumes some memory.
        import platform

        x = platform.system()
        print(x)                   # Darvin
        

08.    datetime

A date in Python is not a data type of its own, but we can import a module named datetime to work with dates as date objects.

        import datetime     #built-in module 
        print("datetime is " + str(type(datetime)))      #module

        # lab 1:    now()
        x = datetime.datetime.now()        # create datetime object

        print("datetime.datetime is " + str(type(datetime.datetime))) #type
        print(type(datetime.datetime.now))    # function or method
        print(x)       #2018-12-15 18:02:46.402374
        print(type(x))           #an object with type datetime.datetime
        print(x.year)            #2018,  its property


        # lab 2:    creating datetime object
        y = datetime.datetime(2020, 5, 17)        # This is an Date object
        print(y)       # 2020-05-17 00:00:00


        # lab 3:   The datetime object has a method, strftime()
        #          for formatting date objects into readable strings,
        #          taking one parameter, format,specifying which part of data you want.
        print(x.strftime("%A"))        # Saturday     %A for weekday
        

09.    json

        # ----   Convert from JSON to Python:   --------------------------
        import json                                     # built-in module
        print("type of json is " + str(type(json)))     # module

        # some JSON:                     the json data wrapped with single quotes
        x =  '{ "name":"John", "age":30, "city":"New York"}'  

        # parse x:
        y = json.loads(x)

        # the result is a Python dictionary:
        print(y["age"])                                 # 30



        # ---- Convert a Python object containing all the legal data types: ----
        import json

        x = {
          "name": "John",
          "age": 30,
          "married": True,
          "divorced": False,
          "children": ("Ann","Billy"),               # python tuple
          "pets": None,
          "cars": [                                  # python list
            {"model": "BMW 230", "mpg": 27.5},          # python dictionary
            {"model": "Ford Edge", "mpg": 24.1}         # python dictionary
          ]
        }

        # use four indents to make it easier to read the result:
        print(json.dumps(x, indent=4))         # a formatted string 
        
        x is  the json data wrapped with single quotes as a string.
        {
            "name": "John",
            "age": 30,  ...
            "children": [                   #json array
                "Ann",                         string element
                "Billy"                        string element
            ],
            "pets": null,
            "cars": [                        #json array
                {
                    "model": "BMW 230",         key-value pair
                    "mpg": 27.5                 key-value pair
                },
                ...
            ]
        }

        

10.    RegEx

        # demo 1  ----------------------------------------------------
        import re

        #Check if the string starts with "The" and ends with "Spain":

        txt = "The rain in Spain"
        x = re.search("^The.*Spain$", txt)

        if (x):
          print("YES! We have a match!")      # YES...
        else:
          print("No match")

        
  • ^   $   .   * are metacharacters
  • ^    Starts with
  • $    Ends with
  • .    Any character (except newline character
  • *    Zero or more occurrences
  • function search returns a match object regarding match info if matched.
        # demo 2  ----------------------------------------------------
        import re
        str = "hello world"
        x = re.search("\s", str)
        if (x):
           print("find it")
        else:
           print("not find it")
        
  • A special sequence is a \ followed by one of the characters in the list below, and has a special meaning:
  • \s: returns a match where the string contains a white space character.
        # demo 3  ----------------------------------------------------
        import re
        str = "The rain in Spain"
        x = re.findall("[arn]", str)
        print(x)    # ['r', 'a', 'n', 'n', 'a', 'n']
        
        
  • The findall() function returns a list containing all matches.
  • A set is a set of characters inside a pair of square brackets [] with a special meaning:
  • [arn] is a set to check if the string has any a, r, or n characters