79
2-Day Python 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

2-Day Python Workshop

  • Upload
    others

  • View
    4

  • Download
    0

Embed Size (px)

Citation preview

Page 1: 2-Day Python Workshop

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

Page 2: 2-Day Python Workshop

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

Page 3: 2-Day Python Workshop

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

Page 4: 2-Day Python Workshop

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

Page 5: 2-Day Python Workshop

File I/O 讀寫文字檔

•打開文件:文件變量名 = open(文件路徑,操作模式)

•讀一行:文件變量名.readline() →一個字串

•讀多行:文件變量名.readlines() →一個列表

•關閉文件:文件變量名.close()

5

操作模式 具體含義

'r' 讀取

'w' 寫入(如文件示不存在會新建一個,如已存在則會覆蓋之前的內容)

'a' 追加(如文件示不存在會新建一個,如已存在則會將內容加到文件末尾)

File object or file handler

Page 6: 2-Day Python Workshop

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!

Page 7: 2-Day Python Workshop

Input Output

File I/O 讀寫文字檔

•去除最尾的換行符’\n’: line.rstrip()

7

https://repl.it/@ShirleySiu/FileIO

Page 8: 2-Day Python Workshop

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.

Page 9: 2-Day Python Workshop

練習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:

Page 10: 2-Day Python Workshop

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

Page 11: 2-Day Python Workshop

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

Page 12: 2-Day Python Workshop

Solution

練習7 – Ans

12

https://repl.it/@ShirleySiu/Ex7-Complete

Sample answer:

Page 13: 2-Day Python Workshop

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

Page 14: 2-Day Python Workshop

為什麼我們要用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.

Page 15: 2-Day Python Workshop

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

Page 16: 2-Day Python Workshop

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

Page 17: 2-Day Python Workshop

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

Page 18: 2-Day Python Workshop

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

Page 19: 2-Day Python Workshop

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

Page 20: 2-Day Python Workshop

Errors in Passing Arguments 傳遞參數的錯誤• When matching is not satisfied

20

TRY IT OUT

Page 21: 2-Day Python Workshop

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

Page 22: 2-Day Python Workshop

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

Page 23: 2-Day Python Workshop

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

Page 24: 2-Day Python Workshop

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!

Page 25: 2-Day Python Workshop

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

Page 26: 2-Day Python Workshop

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)

Page 27: 2-Day Python Workshop

練習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

Page 28: 2-Day Python Workshop

練習8 – Ans

28

https://repl.it/@ShirleySiu/Ex8-Complete

Sample answer:

studInfoSys.pymain.py

Page 29: 2-Day Python Workshop

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

Page 30: 2-Day Python Workshop

Exception 異常

30

• Program stops running where an error happens (runtimeerror 運行時錯誤)

TRY IT OUT

錯誤信息

Type of error: Specifics about the error

Page 31: 2-Day Python Workshop

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.

Page 32: 2-Day Python Workshop

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

Page 33: 2-Day Python Workshop

練習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

Page 34: 2-Day Python Workshop

練習9 - Ans

34

https://repl.it/@ShirleySiu/Ex9-Complete

Sample output

Sample answer:

Page 35: 2-Day Python Workshop

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

Page 36: 2-Day Python Workshop

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

Page 37: 2-Day Python Workshop

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/

Page 38: 2-Day Python Workshop

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

Page 39: 2-Day Python Workshop

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

Page 40: 2-Day Python Workshop

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

Page 41: 2-Day Python Workshop

練習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:

Page 42: 2-Day Python Workshop

練習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:

Page 43: 2-Day Python Workshop

練習10 – Ans

43

https://repl.it/@ShirleySiu/Ex10-Complete

Sample answer:

Page 44: 2-Day Python Workshop

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

Page 45: 2-Day Python Workshop

Operator Overloading運算符重載

• Define operator functions using special method names:

45

Binary operators Comparison operators

Images from https://www.geeksforgeeks.org/operator-overloading-in-python/

Page 46: 2-Day Python Workshop

Operator Overloading Example

46

Overload the equal ‘==‘ operator to compare two points

Create p4, p5, and p6. Compare them using operator ‘==‘ TRY IT OUT

Page 47: 2-Day Python Workshop

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

Page 48: 2-Day Python Workshop

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:

Page 49: 2-Day Python Workshop

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

Page 50: 2-Day Python Workshop

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

Page 51: 2-Day Python Workshop

Fascinated Graphics from Simple Shapes

51

Repeat drawing-and-turn Using different color pens Use different pen sizesTRY IT OUT

Page 52: 2-Day Python Workshop

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

Page 53: 2-Day Python Workshop

Use Function for Repeated Drawing

53

Use function to do repeated drawing (0,0)

(50,50)

TRY IT OUT

Page 54: 2-Day Python Workshop

練習11 -請畫出奧運五環

54

Page 55: 2-Day Python Workshop

練習 – Ans

55

https://repl.it/@ShirleySiu/Ex11-Complete

Sample answer:

hideturtle() can make invisible the turtle

Page 56: 2-Day Python Workshop

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

Page 57: 2-Day Python Workshop

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

Page 58: 2-Day Python Workshop

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

Page 59: 2-Day Python Workshop

Interactive Graphics

3. Repeatedly update the screen display

59

Page 60: 2-Day Python Workshop

練習 - 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

Page 61: 2-Day Python Workshop

Active Turtle Food Eating Game

61

https://repl.it/@ShirleySiu/WalkTurtle

Page 62: 2-Day Python Workshop

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:

Page 63: 2-Day Python Workshop

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

Page 64: 2-Day Python Workshop

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

Page 65: 2-Day Python Workshop

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!

Page 66: 2-Day Python Workshop

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

Page 67: 2-Day Python Workshop

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?

Page 68: 2-Day Python Workshop

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

Page 69: 2-Day Python Workshop

Data Visualization數據可視化

69

A powerful mathematical plotting library

Page 70: 2-Day Python Workshop

First Plot

70

https://repl.it/languages/tkinter

Page 71: 2-Day Python Workshop

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

Page 72: 2-Day Python Workshop

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])

Page 73: 2-Day Python Workshop

First Plot – Labels標籤

73

Page 74: 2-Day Python Workshop

Simple Line Graph

74Save to image fileplt.savefig('line.png', bbox_inches='tight')

Save to image file

https://repl.it/@ShirleySiu/LinePlot

Page 75: 2-Day Python Workshop

Colormaps

• RGB (Red Green Blue)

75

plt.cm.name

More maps are available for reference

Page 76: 2-Day Python Workshop

Simple Bar Chart 條形圖

76

https://repl.it/@ShirleySiu/BarChart

Page 77: 2-Day Python Workshop

Histogram直方圖

77

Page 78: 2-Day Python Workshop

Pie Chart餅形圖

78

Page 79: 2-Day Python Workshop

Thank You

79