<repo_name>amusements/great_shows<file_sep>/py_03_for_else/README.md
[參考網站](https://docs.python.org/3/tutorial/controlflow.html#break-and-continue-statements-and-else-clauses-on-loops)

1. Track & pull branch feature/for_else
2. Copy sample_file.py under the folder py_03_for_else and named as [yourname]_re_rule.py
3. Finish 3 excercises and match the expected output in file.
4. Push/Submit your code to github
<file_sep>/py_03_for_else/sample.py
big_box = ["Orchild", "Mickey Mouse", "Orange", "Cat", "Cow", "Lemon Tree", "Red Pepper"]

# TODO: Using for-loop & continue to add water on plants, but not animal
# OUTPUT:
#   Orchild watered.
#   Orange waterd.
#   Lemon Tree watered.
#   Red Pepper waterd.


# TODO: Using for-loop & break to feed Cow only
# OUTPUT:
#   Cow feeded.


# TODO: Using for-loop & else to wash a car
# OUTPUT:
#   No car to wash.
<file_sep>/py_0501_list_stack/linda.py
# Q1: Define a function which can generate and print a list where the values are square of numbers between 1 and 20. Then the function needs to print the first 5 elements in the list.
# Hint:
#   Use range() for loops.
#   Use list.append() to add values into a list.
#   Use [n1:n2] to slice a list
# OUTPUT:
#   1
#   4
#   9
#   16
#   25
squares = []
for x in range (1,21):
    squares.append(x**2)
print (squares[0:5])

# Q2: Base on Q1, please print the 11th element.
# Hint:
#   Use list.index()
print (squares[11])

# Q3: Base on Q1, reverse list and pop out the top element and print out.
# Hint:
#   Use list.reserse() and list.pop
squares.reverse()
#print (squares)
squares.pop(0)
print (squares)


# Q4: Base on Q1, please insert "I am rock" into 13th position, then print out each element in list.
# Hint:
#   Use list.insert() and for loop
squares.insert(13,"I am rock")
print (squares)
# Q5: Base on Q4, please remove "I am rock", then print out each element in list.
# Hint:
#   Use list.remove()
squares.remove("I am rock")
print (squares)

<file_sep>/py_01_search_text/rika_search.py
inputText = input("Please enter keyword for search: ")

file = open("article.txt", "r")
fileContent = file.readlines()
file.close()

inputTextLower = inputText.lower()
matchedCount = 0;
for line in fileContent:
    for word in line.split():
        wordLower = word.lower()
        matchedCount += wordLower.count(inputTextLower)

print("Keyword {}: We have found {} matched in article".format(inputText, matchedCount))
<file_sep>/linda_practice/linda_re_rule.py
big_box = ["Orchild", "Mickey Mouse", "Orange", "Cat", "Cow", "Leon Tree", "Red Pepper"]
#plants = ["Orchild", "Orange", "Leon Tree", "Red Pepper"]
animals = ["Mickey Mouse", "Cat", "Cow"]
for obj in big_box:
    if (obj != animals):
        print (obj,"watered")
        continue
   

for obj in big_box:
    if (obj == "Cow"):
       print (obj,"feeded")
       break


for obj in big_box:
    if (obj == "car"):
        print (obj,"is a car")
        break
else:
    print ("No car to wash")


<file_sep>/py_0501_list_stack/lily.py
#!/Users/yaliyang/anaconda3/bin/python3

square_list = []

for i in range (1, 21):

    square_list.append(i**2)
    
print (square_list [0:5])

print (square_list [11])

square_list.reverse()

square_list.pop(0)

print (square_list)

square_list.reverse()

square_list.append(400)

print (square_list)

square_list.insert(12, "I am rock")

print (square_list)
   
square_list.remove("I am rock")

print (square_list)


<file_sep>/py_0501_list_stack/daniel.py

result = []
for i in range (1,21):
	a = i**2
	result.append(a)
##Q1
print(result[:5]) 
##Q2
print(result[10]) 
##Q3
result.reverse()
print(result.pop()) 
##Q4
result.insert(12, "I am rock")
print(result)
##Q5
result.remove("I am rock")
print(result)


<file_sep>/py_06_api_practice/daniel.py
import re
import json
import urllib.request, urllib.parse, urllib.error
from datetime import datetime



while True:
	a = "a. 戲劇開始日期與結束日期"
	b = "b. 表演地點"
	search = "請選擇使用何種方式搜尋 (a,b): "
	print(a + "\n" + b)
	searchtype = input(search)
	autotime = "00:00:00"
	get_loc = ""
	dt_start_time = ""
	dt_end_time = ""
	tw_city =("臺北市","台北市","新北市","桃園市","臺中市","臺南市","高雄市","基隆市","新竹市",
	"嘉義市","新竹縣","苗栗縣","彰化縣","南投縣","雲林縣","嘉義縣","屏東縣","宜蘭縣","花蓮縣","臺東縣","澎湖縣")
	if searchtype == "a":	
		while True:
			try:
				get_st_dt = str(input("請輸入欲查詢之開始時間 (YYYY/MM/DD): "))
				dt_start = datetime.strptime(get_st_dt, '%Y/%m/%d')
				dt_start_time = "{} {}" .format(get_st_dt, autotime) 
				break
			except ValueError: 
				print ("開始時間錯誤，請重新輸入一次")

		while True: 		
			try:
				get_end_dt = str(input("請輸入欲查詢之結束時間 (YYYY/MM/DD): "))
				dt_end =  str(datetime.strptime(get_end_dt, '%Y/%m/%d'))
				dt_end_time = "{} {}" .format(get_end_dt, autotime)
				break
			except ValueError:
				print ("結束時間錯誤，請重新輸入一次")
	if searchtype == "b":
		while True:
			get_loc = input("請輸入欲查詢之表演地點（xx 縣 / 市）: ")
			if get_loc not in tw_city:
				print ("沒這種縣市，當什麼假外國人？")
			else:
				break
		break
	else:
		print("你選了什麼鳥？ 重新輸入不然不讓你離開")

url = 'https://cloud.culture.tw/frontsite/trans/SearchShowAction.do?method=doFindTypeJ&category=2'
data = urllib.request.urlopen(url).read().decode()
count = 0
try:
  js = json.loads(data)
except:
  js = None

for item in js:
	for value in item['showInfo']:
		if dt_start_time <= value['time'] <= dt_end_time or get_loc in value['location']:
			title = item['title']
			time = value['time']
			location = value['location']
			print('戲劇名稱:' ,title, '表演地點:',location, '表演時間', time)
			count +=1

else:
	print("搜尋完畢，您的結果有",count,"筆")

<file_sep>/py_02_regular_expression/README.md
[參考網站 1](http://larry850806.github.io/2016/06/23/regex/)
[參考網站 2](https://docs.python.org/3/library/re.html)

1. Track & pull branch feature/regular_expression
2. Create python file under the folder py_02_regular_expression and named as [yourname]_re_rule.py
3. Execute [yourname]_re_rule.py, then prompt a dialog to input the keyword in order to rule the keyword category. (There are 3 categories in total, plz check out the samples.)
4. Print the keyword's category
5. Push/Submit your code to github

Extra bonus (I will value the bonus for whom did it right):
6. Validate the input tw id is effective or not

Output sample 1:
Keyword XXX is a email

Output sample 2:
Keyword XXX is a mobile phone number

Output sample 3:
Keyword XXX is a TW id
<file_sep>/py_02_regular_expression/yiwen_re_rule.py
import re

# DEFINE
inputText = input("Please enter keyword: ")
mailRegular = '^[0-9a-z._+-]*@[a-z0-9]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$'
phoneRegular = '^09[0-9]{8}$'
twIdRegular = '^[A-Z]{1}[0-9]{9}$'
idVerifyDictionary = {"A": "10", "B": "11", "C": "12",
                      "D": "13", "E": "14", "F": "15",
                      "G": "16", "H": "17", "I": "34",
                      "J": "18", "K": "19", "L": "20",
                      "M": "21", "N": "22", "O": "35",
                      "P": "23", "Q": "24", "R": "25",
                      "S": "26", "T": "27", "U": "28",
                      "V": "29", "W": "32", "X": "30",
                      "Y": "31", "Z": "33"}
weight = [1,9,8,7,6,5,4,3,2,1,1]

# FUNCTION(s)
def is_tw_id(inStr):
    head = idVerifyDictionary[inStr[0]]
    body = inStr[1:10]
    e = head + body

    total = 0
    for index, val in enumerate(weight):
        total += (int(val) * int(e[index]))

    if total % 10 == 0:
        print("Keyword {} is a TW id".format(inStr))
    else :
        print("Keyword {} is not TW id".format(inStr))


# MAIN
if re.match(mailRegular, inputText) != None:
    print("Keyword {} is a email".format(inputText))
elif re.match(phoneRegular, inputText) != None:
    print("Keyword {} is a mobile phone number".format(inputText))
elif re.match(twIdRegular, inputText) != None:
    is_tw_id(inputText)
else :
    print("Keyword {} is not matched".format(inputText))
<file_sep>/py_03_for_else/lily_re_rule.py
#!/Users/yaliyang/anaconda3/bin/python3
g_box = ["Orchild", "Mickey Mouse", "Orange", "Cat", "Cow", "Lemon Tree", "Red Pepper"]
# TODO: Using for-loop & continue to add water on plants, but not animal
# OUTPUT:
#   Orchild watered.
#   Orange waterd.
#   Lemon Tree watered.
#   Red Pepper waterd. 

# TODO: Using for-loop & break to feed Cow only
# OUTPUT:
#   Cow feeded.

# TODO: Using for-loop & else to wash a car
# OUTPUT:
#   No car to wash.

#plants = {"Orchild", "Orange", "Lemon Tree", "Red Pepper"}
#animals = {"Mickey Mouse", "Cat", "Cow"}

c_box = {
        "Orchild": "plant", "Mickey Mouse": "animal", "Orange": "plant", "Cat": "animal", 
        "Cow": "animal", "Lemon Tree": "plant", "Red Pepper": "plant"
        }


for key, value in c_box.items():
    if value == "animal":
        continue
    if value == "plant":
        print (key, "watered")


#for i in g_box:
#    if i == "Cow":
#        print ("Cow feeded")
#        break

           
#for i in g_box:
#   if i == "car":
#        print ("car washed")
#else:
#    print ("No car to wash")
    

<file_sep>/py_01_search_text/daniel_search.py
#!/usr/local/bin/python3

''' ----- search practice -----'''

Keyword = input("Type Keyword: ")
k=0
with open("article.txt","r") as f:
	for line in f:
		words = line.split()
		for i in words:
			if (i.lower() ==Keyword):
				k=k+1
	print("We have found", k, "matched in article")<file_sep>/py_03_for_else/Daniel_re_rule.py
big_box = ["Orchild", "Mickey Mouse", "Orange", "Cat", "Cow", "Leon Tree", "Red Pepper"]

# TODO: Using for-loop & continue to add water on plants, but not animal
# OUTPUT:
#   Orchild watered.
#   Orange waterd.
#   Leon Tree watered.
#   Red Pepper waterd.

for item in big_box:
	if item in ["Mickey Mouse", "Cat", "Cow"]:	
		continue
	else:
		print (item + " water")
	#plants = ['Orchild', 'Orange', 'Leon Tree', 'Red Pepper']
	#if item in plants:
	#	print (item + " water")


# TODO: Using for-loop & break to feed Cow only
# OUTPUT:
#   Cow feeded.

for item in big_box:
	if item == "Cow":
		print(item + " feeded")
		break

# TODO: Using for-loop & else to wash a car
# OUTPUT:
#   No car to wash.

for item in big_box:
	if item == "Car":
		print("I found a car")
		break
else:
	print("No car to wash")<file_sep>/py_02_regular_expression/rika_re_rule.py
import re
inputText = input("Please enter keyword: ")
mailRegular = '^[0-9a-z._+-]*@[a-z0-9]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$'
phoneRegular = '^09[0-9]{8}$'
twIdRegular = '^[A-Z]{1}[0-9]{9}$'
idVerifyDictionary = {"A": 10, "B": 11, "C": 12,
                      "D": 13, "E": 14, "F": 15,
                      "G": 16, "H": 17, "I": 34,
                      "J": 18, "K": 19, "L": 20,
                      "M": 21, "N": 22, "O": 35,
                      "P": 23, "Q": 24, "R": 25,
                      "S": 26, "T": 27, "U": 28,
                      "V": 29, "W": 32, "X": 30,
                      "Y": 31, "Z": 33}

def verify_tw_id(tw_id):
    strStrip = tw_id.strip()
    strStripMaxIndex = len(strStrip)-1
    strStripFirstWord = strStrip[0]
    verifyKey = idVerifyDictionary[strStripFirstWord] 
    verifyInt = int(strStrip[strStripMaxIndex])
    verifyInt += int(verifyKey / 10) + (verifyKey % 10) * 9
    i = 8;
    for x in range(1, strStripMaxIndex):
        verifyInt += int(strStrip[x]) * i
        i -= 1
    if verifyInt % 10 == 0:
        return 1
    else :
        return 0

if re.match(mailRegular, inputText) != None:
    print("Keyword {} is a email".format(inputText))
elif re.match(phoneRegular, inputText) != None:
    print("Keyword {} is a mobile phone number".format(inputText))
elif re.match(twIdRegular, inputText) != None:
    if bool(verify_tw_id(inputText)):
        print("Keyword {} is a TW id".format(inputText))
    else :
        print("Keyword {} is not TW id".format(inputText))
else :
    print("Keyword {} is not matched".format(inputText))
<file_sep>/py_0501_list_stack/sample.py
# Q1: Define a function which can generate and print a list where the values are square of numbers between 1 and 20. Then the function needs to print the first 5 elements in the list.
# Hint:
#   Use range() for loops.
#   Use list.append() to add values into a list.
#   Use [n1:n2] to slice a list
# OUTPUT:
#   1
#   4
#   9
#   16
#   25

# Q2: Base on Q1, please print the 11th element.
# Hint:
#   Use list.index()

# Q3: Base on Q1, reverse list and pop out the top element and print out.
# Hint:
#   Use list.reserse() and list.pop

# Q4: Base on Q1, please insert "I am rock" into 13th position, then print out each element in list.
# Hint:
#   Use list.insert() and for loop

# Q5: Base on Q4, please remove "I am rock", then print out each element in list.
# Hint:
#   Use list.remove()
<file_sep>/py_06_api_practice/rika.py
import re
dateRegular = '^[0-9]{4}/[0-9]{2}/[0-9]{2}$'
def check_date_format(dateStr):
    if len(dateStr) == 0:
        return True
    if re.match(dateRegular, dateStr) == None:
        print('dateRegular')
        return False
    dateArr = dateStr.split('/')
    if dateArr[1] < '01' or dateArr[1] > '12' or dateArr[2] < '01' or dateArr[2] > '31':
        print('dateArr')
        return False
    return True

import json
import urllib.request, urllib.parse, urllib.error
def get_josn_data(startDateStr, endDateStr, locationStr):
    sourceURL = "https://cloud.culture.tw/frontsite/trans/SearchShowAction.do?method=doFindTypeJ&category=2"
    source = urllib.request.urlopen(sourceURL)
    decodeSource = source.read().decode()
    sourceJson = json.loads(decodeSource)
    dramaArr = []
    for objDict in sourceJson:
        for infoDict in objDict["showInfo"]:
            location = infoDict["location"]
            if len(locationStr) > 0 and not locationStr in location:
                continue;
            time = infoDict["time"]
            if (len(startDate) > 0 and len(startDate) == len(endDate) and (time < startDate or time > endDate)):
                continue;
            elif (len(startDate) > 0 and time < startDate):
                continue;
            elif (len(endDate) > 0 and time > endDate):
                continue;
            title = objDict["title"]
            locationName = infoDict["locationName"]
            print("Drama Title: ",title)
            print("Time: ",time)
            print("Location: {0} ({1})".format(location, locationName))
            dramaDic = {"title": title, "time": time, "location": location, "locationName": locationName}
            dramaArr.append(dramaDic)
    return dramaArr

startDate = input("Please enter start date for search(EX: 2018/01/01): ")
endDate = input("Please enter end date for search(EX: 2018/01/01): ")
location = input("Please enter location for search(EX: 國家戲劇院): ")
print('Searching..............')
errorMsg = ''
if not check_date_format(startDate) or not check_date_format(endDate):
    errorMsg = "Start date or end date has wrong format!\nDate format should be like 2018/01/01"
elif len(startDate) > 0 and len(endDate) > 0 and startDate > endDate:
    errorMsg = "Start date must be earlier than end date."

if len(errorMsg) > 0:
    print('Error: ',errorMsg)
else:
    resultArr = get_josn_data(startDate, endDate, location)
    print("Total result count: {0}".format(len(resultArr)))
<file_sep>/py_06_api_practice/test.py
import datetime
import json
import urllib.request, urllib.parse, urllib.error
import sys

inputStart = input("Please enter start date for search: ")
inputEnd = input("Please enter end date for search: ")
inputLocate = input("Please enter location for search: ")
#sys.exit(inputText)

url = "https://cloud.culture.tw/frontsite/trans/SearchShowAction.do?method=doFindTypeJ&category=2"
data_str = urllib.request.urlopen(url).read().decode()
data = json.loads(data_str)

count = 0
for obj in data:
    if inputEnd >= obj["startDate"] and inputStart <= obj["endDate"]:
        for info in obj["showInfo"]:
            if inputLocate in info["location"]:
                count +=1
                print(info["time"], ', ', obj["title"], ', ', info["location"])
print("Total count:", count)<file_sep>/py_06_api_practice/README.md
##[Reference Website] 
https://docs.python.org/3/tutorial/datastructures.html 5.5 dictionaries, 5.6 looping
https://docs.python.org/3/library/json.html import json
https://docs.python.org/3/library/urllib.html import urllib

##Hand-in instruction 

1. Pull master branch and find the new folder, `py_06_api_practice`.
2. Create your own branch named it as `[your name]_api_drama` based on master
3. Read through 'README.md' file
4. Name your homework file as `[your name].py`
5. Commit your homwork file to local branch
6. Push your branch to remote
7. Create PR and add reviewer on Github

In this Assignment, you will need to use python to extract data from JSON, one of the most popular format of API.

##Deliverable: 
Use python to call API and display the following details:
1. Drama Title
2. Location
3. Performance time (greater than 2018/01/01 00:00:00)
4. Total count of dramas with different time (same drama but different time are different counts)

##Materials:
API: https://cloud.culture.tw/frontsite/trans/SearchShowAction.do?method=doFindTypeJ&category=2 (Highly recommend to install Chrome extension JSONView to have a better look at data structure)

##Time estimation: 0.5 to 1.5 hours

##Limitation:
None, do whatever you like as long as you can extract and display the deliverable. 
##!!CAUTION!! Hard-code may serious affect the performance and get BOOs from other people!

##Assignment instruction 
You may found helpful `Sample code below but suggest follow the step and try it first`

1. Import libraries json urllib mentioned at reference
2. Open,read and decode the API url, you may use print to test and found something like

```
0:00"}],"showUnit":"","discountInfo":"","descriptionFilterHtml":"","imageUrl":"","masterUnit":[],"subUnit":[],"supportUnit":[],"otherUnit":[],"webSales":"https://www.accupass.com/event/1806181412251090157280","sourceWebPromote":"","comment":"","editModifyDate":"","sourceWebName":"花蓮縣文化局","startDate":"2018/08/22","endDate":"2018/08/22","hitRate":0},{"version":"1.4","UID":"5b55bd96d083a3989c55aa14","title":"107年花蓮漫畫夏令營","category":"2","showInfo":[{"time":"2018/08/02 00:00:00","location":"花蓮市中山路71號","locationName":"花蓮鐵道文化園區一館中山堂","onSales":"N","price":"","latitude":null,"longitude":null,"endTime":"2018/08/21 00:00:00"}],"showUnit":"","discountInfo":"","descriptionFilterHtml":"","imageUrl":"","masterUnit":[],"subUnit":[],"supportUnit":[],"otherUnit":[],"webSales":"https://www.facebook.com/fishanima/","sourceWebPromote":"","comment":"","editModifyDate":"","sourceWebName":"花蓮縣文化局","startDate":"2018/08/02","endDate":"2018/08/21","hitRate":0}]
```

3. Extract JSON object by using json.loads function 
4. Write loop to get the target details and counts `Hint: Review the 5.5 and 5.6`








```Sample Code, please replace 'something'```

import json
import urllib.request, urllib.parse, urllib.error
urllib.request.urlopen('something')
'something'.read().decode()
json.loads('something')


<file_sep>/py_06_api_practice/lily.py
#!/Users/yaliyang/anaconda3/bin/python3
import re
import json
import urllib.request, urllib.parse, urllib.error
drama= urllib.request.urlopen('https://cloud.culture.tw/frontsite/trans/SearchShowAction.do?method=doFindTypeJ&category=2 ')
drama_list= drama.read().decode()
total_list=json.loads(drama_list) 

city = input("City/County:")
start= input("Start date(0000/00/00 00:00:00):")
end= input("End date(0000/00/00 00:00:00):")
theater = input("Theater:")

if len(city) ==0:
    print("You have to fill all the information needed!")
elif len(start) ==0:
    print("You have to fill all the information needed")
elif len(end) ==0:
    print("You have to fill all the information needed")
elif len(theater) ==0:
    print("You have to fill all the information needed")

for dramadict in total_list:
    for infodict in dramadict["showInfo"]:
        title = dramadict["title"]
        time = infodict["time"]
        location = infodict["location"] 
        locationName = infodict["locationName"]
        price = infodict["price"]   
#        recity = re.sub("台", "臺", str(infodict["location"]))
        if (city in infodict["location"]) and (start <= infodict["time"] <= end) and (theater in infodict["locationName"]):
                print ("Drama Title:", title)
                print ("Performance time:", time)
                print ("Theater: {0} ({1})".format(locationName, location))
                print ("Price:", price)           
        


<file_sep>/py_01_search_text/linda_search.py
word = format(input('Input yout word: ')).lower()
with open('article.txt','r') as f:
    for line in f:
        if word in line.lower():
                print ("keyword",(word),":We have found",(sum(line.count(word) for line in f)),"matched in article")<file_sep>/README.md
# great_shows
Collection of performance in Taiwan with nice data format.
<file_sep>/py_02_regular_expression/daniel_re_rule.py
#!/usr/local/bin/python3

import re
Keyword = input("Please tpye the keyword: ")
Email = re.match("[^@]+@[^@]+\.[^@]+",Keyword)
Phone = re.match("^09\d{8}",Keyword)
TWID = re.match("^[A-Z][12][0-9]{8}$",Keyword)
def letter(x):
	return{
	"A":10,
	"B":11,
	"C":12,
	"D":13,
	"E":14,
	"F":15,
	"G":16,
	"H":17,
	"I":34,
	"J":18,
	"K":19,
	"L":20,
	"M":21,
	"N":22,
	"O":35,
	"P":23,
	"Q":24,
	"R":25,
	"S":26,
	"T":27,
	"U":28,
	"V":29,
	"W":32,
	"X":30,
	"Y":31,
	"Z":33,
	}[x]

def TWID(x):
	letter_str = int(str(letter(Keyword[0]))+(Keyword[1:]))  #Change letter to number and merge w/ rest ID number
	letter_list = list(map(int,str(letter_str))) #Convert letter_str to list for calculation
	num = [1,9,8,7,6,5,4,3,2,1,1] #ID check rule
	verify = list(map(lambda x,y:x*y,letter_list,num)) #multiply ID w/ checkrule
	if sum(verify)%10 == 0:
		print (Keyword, "is a valid TWID")
	else:
		print(Keyword, "is not a valid TWID")
if Email:
	print(Keyword, "is an email address")
elif Phone:
	print(Keyword, "is an mobile phone number")
elif TWID:	
	TWID(Keyword)
elif ValueError:
	print("Can't verify the Keyword")

'''
#--------list multiply test------


a = [1,2,3]
b = [4,5,6]
c = list(map(lambda x,y:x*y,a,b))

print(reduce(lambda x,y:x*y,c))
'''


<file_sep>/py_0501_list_stack/assignment.md
[參考網站](https://docs.python.org/3/tutorial/datastructures.html#using-lists-as-stacks)

1. Pull master branch then you will see the new folder, `py_0501_list_stack`.
2. Create your own branch named it as `[your name]_list_stack` based on master
3. Read through 'assignment.md' file
4. Name your homework file as `[your name].py`
5. Commit your homwork file to local branch
6. Push your branch to remote
7. Create PR and add reviewer on Github

#### Q1: Define a function which can generate and print a list where the values are square of numbers between 1 and 20. Then the function needs to print the first 5 elements in the list.
```
* Hint:
*   Use range() for loops.
*   Use list.append() to add values into a list.
*   Use [n1:n2] to slice a list
```

#### Q2: Base on Q1, please print the 11th element.
* Hint: Use list.index()

#### Q3: Base on Q1, reverse list and pop out the top element and print out.
* Hint: Use list.reserse() and list.pop

#### Q4: Base on Q1, please insert "I am rock" into 13th position, then print out each element in list.
* Hint: Use list.insert() and for loop

#### Q5: Base on Q4, please remove "I am rock", then print out each element in list.
* Hint: Use list.remove()
<file_sep>/py_03_for_else/rika_re_rule.py
big_box = ["Orchild", "Mickey Mouse", "Orange", "Cat", "Cow", "Lemon Tree", "Red Pepper"]
animal = ["Mickey Mouse", "Cat", "Cow"]


# TODO: Using for-loop & continue to add water on plants, but not animal
# OUTPUT:
#   Orchild watered.
#   Orange waterd.
#   Lemon Tree watered.
#   Red Pepper waterd.
def add_water_on_plants():
    for thing in big_box:
        if thing in animal:
    	    continue
        print(thing)

# TODO: Using for-loop & break to feed Cow only
# OUTPUT:
#   Cow feeded.
def feed_cow():
    for thing in big_box:
        if thing == "Cow":
            print(thing+" feeded")
            break

# TODO: Using for-loop & else to wash a car
# OUTPUT:
#   No car to wash.
def wash_car():
    for thing in big_box:
        if thing == "Car":
            break
    else:
        print("No car to wash")

print("[Practice 1] Using for-loop & continue to add water on plants, but not animal")
add_water_on_plants()
print("\n[Practice 2] Using for-loop & break to feed Cow only")
feed_cow()
print("\n[Practice 3] Using for-loop & else to wash a car")
wash_car()
<file_sep>/py_02_regular_expression/linda_re_rule.py
word = input('Input your word:').strip()
import re
phoneRegular = re.compile('^09\d{8}$')
phoneMatch = phoneRegular.match(word)
idRegular = re.compile('^[A-Z]\d{9}$')
idMatch = idRegular.match(word)
emailRegular = re.compile('^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$')
emailMatch = emailRegular.match(word)

if phoneMatch:
    print ("keyword",word,"is a mobile phone number.")
elif idMatch:
    print ("keyword",word,"is a id.")
elif emailMatch:
    print ("keyword",word,"is a email.")
else:
    print ("error!")<file_sep>/py_01_search_text/lily_search.py
#!/Users/yaliyang/anaconda3/bin/python3

file = open('article.txt','r')

word = file.read()

file.close

show = input("Keyword : " ) 

output = word.count(show)

print("Keyword", show, ":", "We have found", output, " matched in the article")

 
<file_sep>/py_06_api_practice/linda.py
import re
import datetime
import urllib.request
import json

StartDate = input('輸入開始時間：')
EndDate = input('輸入結束時間：')
Location = input('輸入地點：')

TimeRegular = re.compile(('[0-1][0-9]|2[0-3])\/[0-5][0-9]\/[0-5][0-9]')
TimeMatch = TimeRegular.search(StartDate,EndDate)
if TimeMatch:
	return True
else:
	print ("error!")

response = urllib.request.urlopen('https://cloud.culture.tw/frontsite/trans/SearchShowAction.do?method=doFindTypeJ&category=2')
response = response.read().decode('utf-8')
responseJason = json.loads(response)
for dataDict in responseJason:
	if EndDate >= obj["startDate"] and StartDate <= obj["endDate"] :
		for infoDict in dataDict["showInfo"]:
			if Location in info["location"]:
			print("Drama Title: "+title)
			print("Location: {0} ({1})".format(locationName, location))
			print("Performance time: "+time)
else:
	print("找不到資料")
<file_sep>/py_07_database_sqlite/README.md
##[Reference Website] 
https://pythonspot.com/python-database-programming-sqlite-tutorial/

##Hand-in instruction 
1. Pull master branch and find the new folder, `py_07_database_sqlite`.
2. Create your own branch named it as `[your name]_database_sqlite` based on master
3. Read through 'README.md' file
4. Name your homework file as `[your name].py`
5. Commit your homwork file to local branch
6. Push your branch to remote
7. Create PR and add reviewer on Github

##Materials:
API: https://cloud.culture.tw/frontsite/trans/SearchShowAction.do?method=doFindTypeJ&category=2 (Highly recommend to install Chrome extension JSONView to have a better look at data structure)

##Assignment instruction 
1. Import libraries json, urllib mentioned, sqlite3, sys at reference
2. Call API and get JSON object (If you forget how to do, you can check out 'py_06_api_practice' homework.)
3. Create database named `[your name].db`
4. Create table named 'Dramas' into `[your name].db`. Table Dramas has data fields 'UID', 'Title', 'Category' and data type should the same as JSON object
5. Insert 'UID', 'title', 'category' value from JSON object to table Dramas
6. Display number of all data count from database table Dramas




<file_sep>/py_0501_list_stack/rika.py
def list_stack():
# Q1: Define a function which can generate and print a list where the values are square of numbers between 1 and 20. Then the function needs to print the first 5 elements in the list.
# Hint:
#   Use range() for loops.
#   Use list.append() to add values into a list.
#   Use [n1:n2] to slice a list
# OUTPUT:
#   1
#   4
#   9
#   16
#   25
    squares = []
    for i in range(1, 21):
        squares.append(i*i)
    print("First 5 elements are ",squares[0:5])

# Q2: Base on Q1, please print the 11th element.
# Hint:
#   Use list.index()
    print("The 11th element is ",squares[11])

# Q3: Base on Q1, reverse list and pop out the top element and print out.
# Hint:
#   Use list.reserse() and list.pop
    squares.reverse()
    print("Pop out the top element of reverse list is ",squares.pop(0))

# Q4: Base on Q1, please insert "I am rock" into 13th position, then print out each element in list.
# Hint:
#   Use list.insert() and for loop
    squares.insert(13, "I am rock")
    print("List did insert element: ", squares)

# Q5: Base on Q4, please remove "I am rock", then print out each element in list.
# Hint:
#   Use list.remove()
    squares.remove("I am rock")
    print("List did remove element: ", squares)

list_stack()
<file_sep>/py_06_api_practice/README2.md

1. you will use the same file as previous HW used.
2. Allow user to input start date, end date, location and display the result.
3. Diplay error msg when type in wrong information or no results.<file_sep>/py_02_regular_expression/lily_re_rule.py
#!/Users/yaliyang/anaconda3/bin/python3

import re

test_dialog = input ("Keyword : ")

emailReg = '^\w+@[A-Za-z0-9]*.[A-Za-z]{3}$'

cellphoneReg = '^09[0-9]{8}$'

IDReg = r'^[A-Z]{1}[12]{1}\d{8}$'

dic_alphabet = {'A': '10', 'B': '11', 'C': '12', 'D': '13', 
                'E': '14', 'F': '15', 'G': '16', 'H': '17', 
                'I': '34', 'J': '18', 'K': '19', 'L': '20', 
                'M': '21', 'N': '22', 'O': '35', 'P': '23', 
                'Q': '24', 'R': '25', 'S': '26', 'T': '27', 
                'U': '28', 'V': '29', 'W': '32', 'X': '30', 
                'Y': '31', 'Z': '33'}  
weight = [1, 9, 8, 7, 6, 5, 4, 3, 2, 1, 1]


def is_id(inStr):
    cha_first = dic_alphabet[inStr[0]]
    body = inStr[1:10]
    all = cha_first + body
    
    total = 0

    for index, val in enumerate(weight):
        total += (int(val) * int(all[index]))

    if total % 10 == 0:
        print ("This is a Taiwanese Id.")   
    
    else :
        print ("incorrect")


if re.match(emailReg, test_dialog) != None:

    print ('Keyword', test_dialog, 'is an email')

elif re.match(cellphoneReg, test_dialog) != None:

    print ('Keyword', test_dialog, 'is a cellphone number')

elif re.match(IDReg, test_dialog) != None:

     is_id(test_dialog)

else:
    print('Invalid')
    




    








