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.
the folder structure as below: folder: lab_subdir folder: mydir file: myMath.py file: main.py
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.
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.
# 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")
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)
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()
# 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.
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 |
ref: my topic 30 - 05
#------------ 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
#------------ 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))
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
# --- 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.
import platform x = platform.system() print(x) # Darvin
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
# ---- 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 }, ... ] }
# 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")
# demo 2 ----------------------------------------------------
import re
str = "hello world"
x = re.search("\s", str)
if (x):
print("find it")
else:
print("not find it")
# demo 3 ---------------------------------------------------- import re str = "The rain in Spain" x = re.findall("[arn]", str) print(x) # ['r', 'a', 'n', 'n', 'a', 'n']