僅為學習過程中的隨手筆記。
-
初階練習(Day1~Day14)
-
中階練習(Day15~Day57)
-
高級練習(Day57~Day79)
-
專業練習(Dat80~Day100)
1 2 3 4 5 6 7 8 9 10 Day 1 Day 2 Day 3 Day 4 Day 5 Day 6 Day 7 Day 8 Day 9 Day 10 Day 11 Day 12 Day 13 Day 14 Day 15 Day 16
- 線上 IDE:https://repl.it/
- 友善初學者的 IDE :https://thonny.org/
- 資料型態:
- 數值:
int()、float() - 字串:
str() - 列表:
list[] - 集合:
set{}- 運算
- 聯集
| - 交集
& - 差集
- - XOR
^
- 聯集
- 運算
- 元組:
tuple() - 字典:
{} - 布林值:True、False
print(str1 + str2)及print(str1, str2)的差異
- 數值:
- 運算子:+、-、*、/、//、%
input()print()
Side Project:
- 運算子的運用
- f-string
round( float, decimal places):浮點數的小數位數
Side Project:
- if/elif/else
str.count( sub, start = 0, end = len(string) )
Side Project:
-
import random- Wiki - Mersenne Twister
- Pseudorandom number generators
random.randint(a, b): random integer belongs to [a, b]random.random(): [0, 1) 之間隨機的浮點數random.uniform(a, b): [a, b]中隨機的浮點數
-
sorted():重新排列大小sorted和sort的差異
-
list = [] -
新增自己的 module: 開新 .py 檔案(如:mymodule.py) ---- mymodule.py ---- pi = 3.1415926
print( mymodule.pi ):叫出 mymodule.py 中的 pi 函數 -
反思
- 若事先決定「贏」、「輸」、「平手」,搭配 array 的可行性?
Side Project:
- ';--have i been pwned?
for迴圈range()
Side Project:
- Reeborg's World - Maze
- Tips:walk along the right-hand side ( or left-hand side ) wall.
-
- 紀錄思路,結合所學完成此遊戲。
- tool - flow chart maker
- 此字庫與ASCII可自行更換。
-
反思
- 改成 Bulls and cows?
Side Project:
- creat a function
1.
# def function def func(): to do # call function func()
# def function with 2 or more parameters def greet_with(name=" ", location=" "): print (f"Hello {name}!") print (f"Welcome to {location}!") # call function greet_with(location="TAIWAN", name = "Chi-Ling")
- Wiki - Caesar cipher
Side Project:
- dictionary
# build a dictionary programming_dict = { "Bug":"An error in a program that prevents the program from running as expectrd.", "Function":"A piece of code that you can easily call over and over again." } # retreive an item from the dictionary # fetching by key - should type exactly correct programming_dict["Bug"] # adding new items to dictionary programming_dict["Loop"] = "The action of doing something over and over again." # creating an empty dictionary empty_dict = {} # wipe an existing dictionary programming_dict = {} # editing an item in dictionary programming_dict["Bug"] = "A moth in your computer." # loop through a dictionary for thing in programming_dict: print(thing) # print all keys print(programming_dict[thing]) # print all values
- nesting
字典的
value有許多種形式,如下:{ key1:value1, key2:[List], key3:{Dict} }- Nesting dictionary in a dictionary
travel_log = { "China": {"cities_visited": ["Shanghai", "Beijin", "Nanjin"], "total_visits": 7}, "Japan": {"cities_visited": ["Tokyo", "Osaka"], "total_visits": 2} }
- Nesting dictionary in a list
travel_log = [ { "country": "China", "cities_visited": ["Shanghai", "Beijin", "Nanjin"], "total_visits": 7 }, { "country": "Japan", "cities_visited": ["Tokyo", "Osaka"], "total_visits": 2 } ]
- Nesting dictionary in a dictionary
- VISUALIZE CODE EXECUTION
- 與 Thonny 相似
Side Project:
- Function
Format Name
string.capitalize()及string.title()的應用return紀錄 function 的回傳值,同時結束該 function,意即:不論return後還有多少指令,皆不執行。
- Docstring
def func(a, b): """docstring""" define func(a, b) here
Side Project:
- 綜合前面 10 天內容,完成簡單的 Blackjack 遊戲。
- 實際玩玩看:Online Free Blackjack
- Regularly test your code so that you don't wait until the end when they're a lot of problem.
- To do list
- Deal both user and computer a starting hand of 2 random card values.
- Detect when computer or user has a blackjack. (Ace + 10 value card).
- If computer gets blackjack, then the user loses (even if the user also has a blackjack). If the user gets a blackjack, then they win (unless the computer also has a blackjack).
- Calculate the user's and computer's scores based on their card values.
- If an ace is drawn, count it as 11. But if the total goes over 21, count the ace as 1 instead.
- Reveal computer's first card to the user.
- Game ends immediately when user score goes over 21 or if the user or computer gets a blackjack.
- Ask the user if they want to get another card.
- Once the user is done and no longer wants to draw any more cards, let the computer play. The computer should keep drawing cards unless their score goes over 16.
- Compare user and computer scores and see if it's a win, loss, or draw.
- Print out the player's and computer's final hand and their scores at the end of the game.
- After the game ends, ask the user if they'd like to play again. Clear the console for a fresh start.
Side Project:
- Scope
- local scope: exist within functions
- global scope
- difference: where you define or where you create the variables or the functions
- name space
- Dose Python have block space? ans: NO. But in C++, Java, etc.
- 如果要在自訂函數中呼叫 global variable?
enemies = 1 def increase_enemies(): global enemies ### 在函數中使用 global 呼叫該變數 enemies += 1
- 但缺點是容易混淆甚至產生 bug,故應盡量避免使用。
- Avoid modifying global variable.
- 替代方案 使用
return
def increase_enemies(): return enemies + 1 enemies = increase_enemies()
- Python constants and global scope
- globe variable 應小心使用
- 但可以用在不變的常數,如:PI。(使用上習慣全大寫拼寫,以利分辨。)
- Text to ASCII Art Generator(TAAG)
Side Project:
-
Steps to Debug
It's an important part of every programmer's journey.
- Describe the problem.
Untangle the problem and try to make sense of what's going on.
- Reproduce the bug.
Sometimes the bug not show up in the first time.
- Play computer.
- Fix the errors
- Use
print(). - Use a debugger.
Python Tutor (onlone debugger)
- Take a break.
- Ask your friend.
- Run often.
If you do end up in that situation and you can see multiple bugs at the same time, try to tackle them one at a time instead of trying to do bits and bobs of each.
- Ask Stack Overflow.
- Describe the problem.
- 玩玩看:The Higher Lower Game
- Step 1. 觀察遊戲規則,完成 flow chart
- Step 2. Break down the problem
- Step 3. To - do list
- 讀取
game_data.py資料 (a list of a dictionary) - 將字典中資訊組成語句印出
input()使用者猜測值- 比較、印出猜測結果
- 讀取
- Step 4. Turn the problem into comments
Side Project:
-
IDE, Integrated Development Environment
- Download Python:https://www.python.org/downloads/
"Disable path length limit." → (click) → "Do you want to allow this app to make changes to your device?" → (click 'Yes')
- Install PyCharm (Community is FREE):https://www.jetbrains.com/pycharm/download/
- Build-in Linter
- Local history:Last 12 hours
- View structure
- Refactor rename
- PyCharm keyboard shortcut - Running and debugging
- Build-in Linter
- Download Python:https://www.python.org/downloads/
-
emoji
-
Coffee Machine Program Requirements
- 根據此表完成Coffee Machine
好用技巧:多行編輯
- Windows -
Alt+shift- Mac -
option+shift
Side Project:
- OOP, Object Oriented Programming 物件導向程式設計
- 將任務切成數個小任務,針對各任務目的模組化
- 餐廳經理 → 餐廳員工(門口接待、服務生、廚師、清潔人員...)
- Procedural Programming 程序式程式設計
- 過程呼叫、函式呼叫
- 一人餐廳 → 一人完成點餐、廚師、送餐、清潔等工作
- How to use OOP?
- eg. waiter
1. Attributes - what it has?
is_holding_plate = Truetables_responsible = [4, 5, 6]2. Methods - what it does?def take_order(table, order):def take_payment(amount):
- Class(Pascal Case)
rf:Camel case > upper camel case - 同一模組(Class,
CarBlueprint())可以生成多個版本(Object,car) -car = CarBlueprint()
- Turtle Graphics
Object.AttributeObject.Method
- Pypi.org
prettytable
Side Project:
Classis a blueprint for creating an eventual object- Create
class
- Create
PascalCasevs.camelCasevs.snake_case
PascalCasefor class name, andsnake_casefor anything else in Python.
- OPEN TRIVIA DATABASE
- API 生成的資料為
json格式,再依據內容更改相對應的關鍵屬性即可。
- API 生成的資料為
Side Project:
- Turtle Graphics, Tuples and Importimg Modules
pencolor(colorstring): Set pencolor to colorstring, which is a Tk color spacification string, such as'red','yellow', or'#33cc8c'- rf:
turtle.pencolor(*args) - Tk = tkinter (module)
- GUI = Graphical User Interface
- rf:
- CS111 = Turtle Colors
- Colors
-
common seperated values
-
weather_data.csv
day temp condition Monday 12 Sunny Tuesday 14 Rain Wednesday 15 Rain Thursday 14 Cloudy Friday 21 Sunny Saturday 22 Sunny Sunday 24 Sunny to-do 1
- open up this file.
- add each line of data into a list which we'll called data.
# 讀取 .csv 檔,存在 data with open(".py\\weather_data.csv") as data_file: data = data_file.readlines() print(data)
-
import pandas -
2018 Central Park Squirrel Census - Squirrel Data
- 計算各毛色數量
只有三種顏色 ||Primary Fur Color|Count| |:---:|:---:|:---:| |0|Gray|| |1|Cinnamon|| |2|Black||
- 計算各毛色數量
Side Project