Upload
others
View
9
Download
0
Embed Size (px)
Citation preview
2-DayPython Workshop
Instructor: Shirley Siu, University of Macau
Teaching Assistant: Giotto Tai, University of Macau
{shirleysiu,hiokuantai}@umac.mo
Slides co-developed by Shirley and Giotto 1
Link to Workshop Material is accessible at https://repl.it/@ShirleySiu/Starter
Day 1
• Introduction
• Elements of Programs
• Conditional Statements
• Loops (For, While)
• Lists and Tuples
• Dictionaries
• File I/O
• Functions & Modules
• Exceptions
• Classes and Objects
• Turtle Graphics
• Data Visualization
2
Day 2
Day 1
• Introduction
• Elements of Programs
• Conditional Statements
• Loops (For, While)
• Lists and Tuples
• Dictionaries
• File I/O
• Functions & Modules
• Exceptions
• Classes and Objects
• Turtle Graphics
• Data Visualization
3
Day 2
About Files 關係文件
• When a program is running, data is stored in random access memory (RAM) 隨機存取存儲器
• RAM is fast but volatile 揮發性的
• By reading and writing files, programs can save information between program runs.
4
File I/O 讀寫文字檔
•打開文件:文件變量名 = open(文件路徑,操作模式)
•讀一行:文件變量名.readline() →一個字串
•讀多行:文件變量名.readlines() →一個列表
•關閉文件:文件變量名.close()
5
操作模式 具體含義
'r' 讀取
'w' 寫入(如文件示不存在會新建一個,如已存在則會覆蓋之前的內容)
'a' 追加(如文件示不存在會新建一個,如已存在則會將內容加到文件末尾)
File object or file handler
File I/O 讀寫文字檔
6
Input Output
https://repl.it/@ShirleySiu/FileIO
Newline character ‘\n’ is part of the string, that’s why the extra new line!
Input Output
File I/O 讀寫文字檔
•去除最尾的換行符’\n’: line.rstrip()
7
https://repl.it/@ShirleySiu/FileIO
File I/O 讀寫文字檔
• A standard code block to write to a file:
8
savedata.txt
• A standard code block to read from a file, and manage it line-by-line:
Use the with statement for better syntax and exception handling
No need to close the file, it will be done automatically.
練習7 –計算平均分
•讀入成績表文件,並計算每個學生的平均分
9
scores.txt
Console Output
Rounding output to 2 decimal placesRemember to convert str into intbefore calculation
Split line by space
https://repl.it/@ShirleySiu/Ex7
See next slides for some tips for functions
Template code to get started:
Some Functions for String: strip, split, join
• 删除字符串末尾的字符
• Use str.rstrip() to remove ‘\n’ at the end of the string
• str.rstrip()
• 通過指定分隔符對字符串進行切片
• Use str.split(<delim>) to split a string into list of data separated by the delimiter
• str.split()• str.split(‘;’)
• 把切片的元素再連接在一起
• Split and Join• ‘ ‘.join(str.split())
10
TRY IT OUT
Rounding & Quick Handling of List into List
•四舍五入
• Use round(float, decp) to round a value into num of decimal places
• To round a whole list of values, put results into a list:
[ func(var) for var in list ]
11
TRY IT OUT
Solution
練習7 – Ans
12
https://repl.it/@ShirleySiu/Ex7-Complete
Sample answer:
Day 1
• Introduction
• Elements of Programs
• Conditional Statements
• Loops (For, While)
• Lists and Tuples
• Dictionaries
• File I/O
• Functions & Modules
• Exceptions
• Classes and Objects
• Turtle Graphics
• Data Visualization
13
Day 2
為什麼我們要用Functions函數?
• Code duplication problem重覆問題• A task needs to be performed multiple times
• When program gets longer, difficult to read
14Image from ng-club.info
Each function does one specific job.
Components of a Function函數的組成
15
1. 定義函數 Definition of a function: name, 0 or more parameters
2. 文檔字符串 Docstring (explanation of how to use)
3. 主體 Body
4. 回傳 Return something
https://repl.it/@ShirleySiu/IsEven
Use your function separately TRY IT OUT
Function call
Actual parameter (argument)
Formal parameter
Function Execution 函數的執行
16
def main():
sing('Fred')
print()
sing('Lucy')
def sing(person):
happy()
happy()
happy(person)
happy()
def happy(person=''):
if person:
print('Happy birthday, dear ‘, person,'.', sep='')
else:
print('Happy birthday to you.')
person = “Fred” person = “Fred”
https://repl.it/@ShirleySiu/FunsCall
Control returns to caller and continue
Passing Arguments 傳遞參數
• For >1 parameters, match actual parameters to formal parameters based on:
• Position
• Keyword
17
def describe_person(name, gender)
describe_person(‘Shirley’,’F’)
def describe_person(name, gender)
describe_person(gender=‘F’,name=‘Shirley’)
https://repl.it/@ShirleySiu/DescribePerson
Default Values 默認參數值
• To simplify the function call
• Default value is used when the actual parameter is not given in the function call
18
def describe_person(name, gender=‘F’)
describe_person(‘Shirley’)
e.g. mostly girls, set it as default
describe_person(‘John’,’M’) Specify for exceptional case
Passing Many Arguments 傳遞很多參數
• If the number of arguments is not known in advanced, tell Python to collect as many arguments as the caller provides
19
def describe_many_persons(*names):
for i in names:
print(i)
TRY IT OUT
Errors in Passing Arguments 傳遞參數的錯誤• When matching is not satisfied
20
TRY IT OUT
Return 回傳值• A function can return any kind of value (int, float, or even list, dictionary)
21
TRY IT OUT
The returned list is unwrapped
Dictionary structure is lost
Variable Scope變量的可用範圍
22
def increment(x):
x = x + 1
return x
x = 3
newx = increment(x)
main.py • Scope: places in a program where a given
variable may be referenced
• Variables are in separate scopes (pass by
Values)
increment
x
newx
Global scope
Some code
3
4
x
increment scope
3
Slide modified from MIT 6.0001 LECTURE 4
4
Invoke function
Execute function
Return result
Function scope is destroyed
https://repl.it/@ShirleySiu/Increment
Passing a List has Side Effect 傳遞列表副作用
23
https://repl.it/@ShirleySiu/AddInterest
def add_interest(balances,rate):for i in range(len(balances)):
balances[i] = balances[i]*(1+rate)
amounts = [1000,2200,800,360]rate = 0.05add_interest(amounts,rate)print(amounts)
New values created and got assigned to the list
Old values will be destroyed by Python
How to Prevent Side Effect 如何預防副作用
• Pass a copy of the list to the function
24
add_interest(amounts[:],rate)
amounts = [1000,2200,800,360]rate = 0.05add_interest(amounts,rate)print(amounts)
TRY IT OUT
• Alternatively, when inside the function, copy the list before any operation:
local_amount = amounts[:]
Then only use local_amount inside the function!
Variable Scope 變量的可用範圍
• Inside function, can access a variable in global scope, but cannot modify it (However, proper way is to pass by argument & return)
• 只可訪問/使用全局變量,但不能修改
25
TRY IT OUT
One Step Further – Module模塊
• Put functions into a separate file
• Import into the program
• Call with module_name.function_name()
26
https://repl.it/@ShirleySiu/Module
mylib.py
addition subtraction multiplication
main.py
import mylib
…
mylib.addition(a,b)
mylib.subtraction(a,b)
import mylib as ml
…
ml.addition(a,b)
ml.subtraction(a,b)
from mylib import addition
…
addition(a,b)
練習8 –簡單學生分數系統
• Organize the code of the Student Information System from Ex 5 into module and functions:
• 做用模塊和函數重新組織Ex5的代碼
27
https://repl.it/@ShirleySiu/Ex5-Complete
studInfoSys.py
menu add delete update analyze
main.py
• Getting user input• Call studInfoSys functions• Declare and store data lists
(student_name, student_score)
Copy the code from
練習8 – Ans
28
https://repl.it/@ShirleySiu/Ex8-Complete
Sample answer:
studInfoSys.pymain.py
Day 1
• Introduction
• Elements of Programs
• Conditional Statements
• Loops (For, While)
• Lists
• Dictionaries
• File/IO
• Functions & Modules
• Exceptions
• Classes and Objects
• Turtle Graphics
• Data Visualization
29
Day 2
Exception 異常
30
• Program stops running where an error happens (runtimeerror 運行時錯誤)
TRY IT OUT
錯誤信息
Type of error: Specifics about the error
Exception Handling 異常處理
31
try:# Something that may fail<body>
except <ErrorType>:# Handle the error<handler>
• Encode codes within try-except block
• If error occurs, pass to the handler codes
• Different handlers for different errors
TRY IT OUT
If ErrorType is not specified, all errors will
be handled by the same handler.
Exception Handling 異常處理
• A complete version
• All clauses are optional, except the “try” clause
32
try:# Something that may fail
<body>except <ErrorType>:
# Handle the error<handler>
else:# No failures occur<body>
finally:# Execute always<body>
To clean up the resources, e.g. close the file
練習9 -異常處理
•修改代碼以處理以下兩個錯誤Modify codes to give error messages tailored to the following two errors:
• ZeroDivisionError (e.g. user inputs a 0)
• ValueError (e.g. user inputs “abc” instead of a numeric)
•要求重複輸入,直至輸入無錯
• Repeat asking for input until the input is error free
33
https://repl.it/@ShirleySiu/Ex9
Template code to get started:
Sample output
練習9 - Ans
34
https://repl.it/@ShirleySiu/Ex9-Complete
Sample output
Sample answer:
Raise Exceptions 抛出異常
• If our program detects an error condition, we can raise our own exception.
35
raise ErrorType(error_message)
TRY IT OUT
https://repl.it/@ShirleySiu/RaiseError
Day 1
• Introduction
• Elements of Programs
• Conditional Statements
• Loops (For, While)
• Lists
• Dictionaries
• File I/O
• Functions & Modules
• Exceptions
• Classes and Objects
• Data Visualization
• Turtle Graphics
36
Day 2
Classes and Objects 類和對象
• Classes: represent real-world things, define their general behavior
• Objects: an instance of a class (實例化)
37Image from http://leetusman.com/intermediate-programming/posts/classes-and-objects/
The Dog Class and my_dog Object
38
初始方法(構造器)Initializer method (constructor)• Execute when a new instance of
object is created• Setup the 屬性 attributes’ values (e.g.
name, age)
Self is for referencing to the object instance itself
Class method • Perform operations執行操作• Manipulate attributes操縱屬性
https://repl.it/@ShirleySiu/Dog
The Dog Class and my_dog Object
• Instantiate my_dog (You can create multiple instances)
• Access the object’s attributes
39
• Calling the object’s method
https://repl.it/@ShirleySiu/Dog
TRY IT OUT
The Dog Class and my_dog Object
• Create method and calling it with arguments
40
• Define method __str__ for printing the object
TRY IT OUT
https://repl.it/@ShirleySiu/Dog
練習10 – ”點”類
• Implement the class Point
• Two attributes, x and y
• Five methods:1. __init__ to create new instance of a point. Default to have x=0, y=0, but user can
also give x and y values as parameters建立一個新的物件,使用者可提供x和y的值(默認x=0,y=0)
2. __str__ to return a string describing this point: (x=..., y=…)回傳描述該點的字串,格式: (x=…, y=…)
3. move to assign new values to x and y為x和y分配新的值
4. distance_from_origin to measure the distance of this point to the origin (0, 0)計算該點與原點(0,0)的距離
5. distance_from_point to measure the distance of this point to another point 計算該點與另一個點的距離
41
https://repl.it/@ShirleySiu/Ex10
Template code to get started:
練習10 – ”點”類
42
https://repl.it/@ShirleySiu/Ex10
Template code to get started:
In the main program, we create two different point objects, p1 and p2:
練習10 – Ans
43
https://repl.it/@ShirleySiu/Ex10-Complete
Sample answer:
Function uses and return Objects
• Object can be passed to a function as parameter
• Object can be returned by a function
44
Create a function to calculate mid-location between two points, return this location as a point to the calling function:
Call the function
TRY IT OUT
Operator Overloading運算符重載
• Define operator functions using special method names:
45
Binary operators Comparison operators
Images from https://www.geeksforgeeks.org/operator-overloading-in-python/
Operator Overloading Example
46
Overload the equal ‘==‘ operator to compare two points
Create p4, p5, and p6. Compare them using operator ‘==‘ TRY IT OUT
Day 1
• Introduction
• Elements of Programs
• Conditional Statements
• Loops (For, While)
• Lists
• Dictionaries
• File I/O
• Functions & Modules
• Exceptions
• Classes and Objects
• Turtle Graphics
• Data Visualization
47
Day 2
Turtle
• Virtual turtles 虛擬烏龜 move around the screen
• Draw beautiful shapes with simple graphics
48
https://repl.it/@GiottoTai/SHCC https://repl.it/@GiottoTai/Pikachuhttps://repl.it/@GiottoTai/PeppaPig
Load and Run the following to see how Turtle draws:
Starting Turtle
49
https://repl.it/languages/python_turtle
Use Turtle with the online coding platformScratchTurtle
The arrow is facing East initially, that is the direction of move.
Repeat the line drawing 5 times:
Draw a line and change movementangle:
TRY IT OUT
TRY IT OUT
Turtle Movement
• forward(pixel): Move the turtle forward by some pixels向前走
• backward(pixel): Move the turtle backward by some pixels向後走
• right(deg): Rotate the turtle clockwise by some degrees順時針旋轉
• left(deg): Rotate the turtle anti-clockwise by some degrees逆時針旋轉
• position(): Return current position x, y取得當前位置
50
Each tiny square is a pixel
Fascinated Graphics from Simple Shapes
51
Repeat drawing-and-turn Using different color pens Use different pen sizesTRY IT OUT
Turtle Pen
• pencolor(color-name): Change the colour of the pen改變筆的顏色
• pensize(pixel): Change the size of the pen改變筆的大小
• penup(): Lift the pen so it does not write when move提筆
• pendown(): Put the pen down again落筆
• goto(x,y): Go to the position (x , y)
• circle(radius): Draw a circle畫圓
52
• hideturtle() Make invisible
• showturtle() Make visible
Use Function for Repeated Drawing
53
Use function to do repeated drawing (0,0)
(50,50)
TRY IT OUT
練習11 -請畫出奧運五環
54
練習 – Ans
55
https://repl.it/@ShirleySiu/Ex11-Complete
Sample answer:
hideturtle() can make invisible the turtle
More Colors and Color-Fill
56
t.color(color_name)
t.begin_fill()
<<< normal shape code
goes here >>>
t.end_fill()
color_name
TRY IT OUT
Interactive Graphics
1. Design our own turtle class (ActiveTurtle) which draws in response to user’s action
57
https://repl.it/@ShirleySiu/InteractiveTurtle
ActiveTurtle is a child class of turtle.Turtle, mean it inherits parent’s attributes and methods
One of the methods to move the active turtle
Interactive Graphics
2. Use the screen onkey method to capture user’s action
58
Create an active turtle instance
Obtain the screen object & manipulate the screen attribute, e.g. background color
Define action for a keyboard-event
Set focus on the screen
Interactive Graphics
3. Repeatedly update the screen display
59
練習 - Interactive Graphics
• Complete the implementation of other three onkey actions:• Down
• Left
• Right
• Add and try the onclick method, see what happen to the turtle when you mouse-click on the screen
60
https://repl.it/@ShirleySiu/InteractiveTurtle-Complete
Active Turtle Food Eating Game
61
https://repl.it/@ShirleySiu/WalkTurtle
How to make ActiveTurtle a Game
62
1. Create another turtle object, call it a pen, which is use to draw the food
2. Randomly place some food use the stamp method
Each food location is a string “x:y”
https://repl.it/@ShirleySiu/InteractiveTurtle-CompleteStarting from this code:
How to make ActiveTurtle a Game
63
3. When turtle moves across the food, the food will be redrawn as eaten
4. Add the eatfood function into all actions, e.g.
Try to eat the food at this location
How to make ActiveTurtle a Game
64
5. Add the Food count into eatfood function
6. Add another turtle object to take careof writing the counts
How to make ActiveTurtle a Game
65
7. Similarly, add the timer label
8. Update the timer repeatedly byrecursively calling itself
Add the result label to announce the result when time’s up!
How to make ActiveTurtle a Game
66
10. Start the timer just before the game loop
Hurray! You have completed yourfirst Python Game!
9. When all food is eaten, the player wins! Add this to the eatfood function
More Ways to Improve the Game
• Convert the foodmap, labels, etc. into a Class “GameBoard”
• Use variables instead of constants (different difficulty levels)• How many food to place
• How much time to play
• Add player records and save into file
• Add sound (currently not supported in repl.it, need to do it locally)
• Add player profile (a better image of the turtle, e.g. a nicecartoon)
67
Perhaps as your summer holiday leisure-work?
Day 1
• Introduction
• Elements of Programs
• Conditional Statements
• Loops (For, While)
• Lists
• Dictionaries
• File I/O
• Functions & Modules
• Exceptions
• Classes and Objects
• Turtle Graphics
• Data Visualization
68
Day 2
Data Visualization數據可視化
69
A powerful mathematical plotting library
First Plot – Style
71
Character Description
'-' solid line style
'--' dashed line style
'-.' dash-dot line style
':' dotted line style
Character Description
'.' point marker
',' pixel marker
'o' circle marker
's' square marker
'v' triangle_down marker
Character Color
‘b’ blue
‘g’ green
‘r’ red
‘c’ cyan
‘m’ magenta
‘y’ yellow
‘k’ black
‘w’ white
http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.plot
First Plot – Axes軸
72
plt.ylim(19.8,21.2)
plt.xlim(0.5,4.5)
plt.yticks([20, 21, 20.5, 20.8])
plt.xticks([1,2,3,4])
First Plot – Labels標籤
73
Simple Line Graph
74Save to image fileplt.savefig('line.png', bbox_inches='tight')
Save to image file
https://repl.it/@ShirleySiu/LinePlot
Colormaps
• RGB (Red Green Blue)
75
plt.cm.name
More maps are available for reference
Histogram直方圖
77
Pie Chart餅形圖
78
Thank You
79