# COMP 1021 [python]
###### tags: 'note', 'comp'
## 前情提要 9/3
* programming question wab: Stack Flow
* don't use canvas to contact professor
* lab課如果project作業沒問題就不用去
* submit lab project hw on canvas
## 9/5 L1
### get random int
you get a random number between a and b
(including a and b)
```
import random
random.randint(number_a, number_b)
```
## 9/7 L2
### turtle
```
import turtle
turtle.clear() #clean the canvas
turtle.forward(length)
turtle.backward(length)
turtle.left(degree)
turtle.right(degree)
turtle.goto(x,y)
turtle.tracer(Boolean) #如果放False, 那行開始畫畫軌跡不會出現, 之後再放turtle.tracer(True)才會再出現
turtle.up() #提筆(不會畫出東西)
#turtle.up()的時候turtle.dot(r)還是會畫出東西來
turtle.down() #放筆(開始畫)
turtle.hideturtle() #讓畫筆箭頭不要出現
turtle.showturtle() #讓畫筆箭頭出現
turtle.setheading(degree) #讓畫筆朝向指定方向,譬如設0就是朝正右邊
turtle.width(x) #the width of the line
turtle.color("color") #change the color of the line, e.g. "cyan"
turtle.color("line_color", "fill color")
turtle.begin_fill("color")
#use it before drawing a graph you want to fill it with that color
turtle.end_fill("color")
#use it when finish drawing that graph
turtle.fillcolor("color") #change the fill color
turtle.speed(x) #1<=x<=10, 6 is normal speed
turtle.write("string", font=("Arial", 40, "bold")) #後面那個font是調字體樣式
turtle.circle(x) #x>0時向左畫半徑=x的圓, x<0向右
turtle.circle(x,degree) #圓心在目前點向左x的點,畫degree度的圓弧
turtle.dot(r) #畫半徑=r的實心點點
turtle.setup(width, height) #set the size of the canva
turtle.done() #use it when you're done
```
## loop
### while
* while True: infinite loop
### for
```
for i in range(4):
print(i, end = "- -") #end = "- -": use - - to seperate the numbers
```
#### range
```
print (list(range(1,6))) #print 1 2 3 4 5
range(1, 10, 2) #return 1 3 5 7 9
range(2, 10, 2) #return 2 4 6 8
range(10, 1) #error (the second number should be bigger than the first one)
range(1, 10, 0) #error (the third number can't be zero)
```
#### continue
* 在for loop裡碰到continue的話,在continue之後的東西就不會執行,就是說直接進到下一個 i
* example:
在這個例子裡,會print出0 1 3 4,因為 i = 2的時候,continue讓迴圈跳過後面的print,直接進到 i = 3然後繼續
```
for i in range(5):
if (i==2):
continue
print (i, end=" ")
```
## 9/28
### list
* you can add two list together and the position won't change
```
[2, 4, 6] + [8, 10] = [2, 4, 6, 8, 10]
```
* funtions related to list
```
list.sort() #將list中的數字由小到大排序
list.reverse() #將list中的物件排序倒過來
list.count(x) #數x這個物件在list中出現了幾次
list.index(x) #找出物件x第一次出現的index
list.insert(index, x) #在list[index]插入物件x,後面的物件indexj往後推移1
list.pop(x) #從list中移除index為x的物件,默認為最後一項,但如果是直接print list.pop()就是會輸出那個被刪除的物件
list.remove(x) #從list中移除物件x
list.append(x) #在list的最末端加入物件x
list_a.extend(list_b)把list_a和list_b合併,b接在a的後面
```
* list[-1] refer to the last item in the list
For example, list = [a, b, c, d, e], then list[-1] = list [4] = e, list[-2] = list[3] = d and so on
#### slicing the list
* when you want to print the whole reverse list:
```
l = [a, b, c, d, e]
```
use
```
print (l[4::-1])
```
or
```
print (l[::-1])
```
instead of
```
print (l[4:-1:-1])
# output an empty list []
```
because negative indices have a special meaning in python
(the negative indices count from the last element)
* when you code
```
print (list[11:14])
```
it output items whose index is 11, 12, 13
(doesn't include 14!!!!)
### tuple
* 和list很類似,但是是用()刮起來的
* e.g. tuple = (1,2,3,"Hi")
* 一樣有index,以上面那行的tuple為例,你可以用tuple[3]叫出"Hi"
* Tuples are immutable!(can't be changed) So you can't sort it, add things to it and remove things from it.
* len(), count(), index() work for tuple because these functions won't do any change on tuple while working.
### string
* you can't change the content of string after it is created
```
s = "hello world"
s[3] = k #this is not allowed!!
```
* you can add two string together
* you can multiply the string with a constant (s*n)
## 10/12
* int(x) simply throws away decimal place
* round(x) will round a float to the closest integer
but if it is x.5 (equally close to x and x+1), then it will be round to the closest even integer
```
round(1.2) #return 1
round(1.9) #return 2
round(1.5) #return 2
```
* slide slicing p14 midterm 前看一遍
## 10/17
### type()
return the type of the input
### print()(?
```
#code below works though 21 is integer, and it will have space before and after 21
print("He is",21,"years old")
#code below won't ouput anything, type of all the items should be the same when using +
print("He is" + 21 + "years old")
```
## Midterm past paper questions should be reviewed
* 2021 fall Q5
* 2021 spring Q4
* 2020 fall part2 Q3(原來是少一個顏色的部分==) & Q4
## 10/24
### turtle 2
* original shpaes library that we can use: ["Arrow", "Turtle", "Circle", "Square", "Triangle", "Classic"]
```
t = turtle.Turtle() #create a new turtle called t
turtle.shape("shape") #改變畫筆形狀(就是把箭頭換掉而已)
turtle.addshape("newshape.gif") #把新的圖案加入畫筆形狀庫,只能用gif不能用其他檔案類型
turtle.shapesize(number_a,number_b) #number_a決定width(縱), number_b決定length(橫), 數字越大大小越大
```
#### get informations of the turtle
```
result = thisTurtle.xcor() #get x position
result = thisTurtle.ycor() #get y position
result = thisTurtle.position() #get both x and y
result = thisTurtle.heading() #get heading angle
result = thisTurtle.fillcolor() #get the fillcolor
result = thisTurtle.speed() #get the speed
result = thisTurtle.shape() #get the shape
```
## 10/26
### event handling function
```
turtle_name.on event_name (event_handling_function )
```
#### click event example
```
def drawcircle(x,y):
turtle.circle(250)
turtle_name.onclick(drawcircle)
#turtle will draw a cricle at where you click
```
#### drag event example
```
turtle_name.ondrag(turtle.goto)
#turtle wiil move along the mouse when you drag it
```
#### key pressing event
```
turtle_name.onkeypress(nykeyfunc, 'which key to press')
```
#### turtle.focus()
This function make sure your turtle window has focus so the key presses go to the program
## 10/31
### functions
#### variables
* Local variables: variables created in the function
* Glbal variables: variables created outside of any function
* If a local variable and a global variable have the same name, priotrity is given to the local variable
* You can add the command "global" infront of the variable to specify that you want to make changes on the global variable in an function
* E.g.
1.
```
def magic_trick(money):
if money < 1000:
money = money + 500
money = int(input("How much do you have? "))
magic_trick(money)
print("You have $" + str(money) + " now!")
```
terminal:
*How much do you have? 500
You have 500 now!*
因為在function裡面是對local variable的money造成改變,而print指令裡面用的是global variable的money,所以可以看到上面的bug
2.
```
def magic_trick():
global money
if money < 1000:
money = money + 500
money = int(input("How much do you have? "))
magic_trick()
print("You have $" + str(money) + " now!")
```
terminal:
*How much do you have? 500
You have 1000 now!*
在這個function裡,因為是直接把global variable的money叫出來用,所以就是直接對要被print出來的money做改變,就解決了1.裡出現的問題
#### return
* if there is nothing behind return,
## 11/2
### using other things as True and False
* True: numbers other than 0 / non-empty list, tuple, string
* False: 0 / empty list[], tuple(), string""
## 11/7
### The precedence table

### text
* /t : we use /t as tab in a string in computer programming
one tab space equals to 8 characters space
```
print ("Hello/tworld")
#Hello world
```
* /n : we use /n as a new line character in a sring in computer programming
```
print ("Hello/nworld")
#Hello
#world
```
## 11/9
### string.rstrip()
remove the endline character(\n) and spaces at the end of the string
### turtle.bgcolor(int(red), int(green), int(blue))
用RGB調背景顏色
### string.split(theCharacterForSplitting)
split the string at specific character to a list of strings
## 11/14
### max(list)
If the list contains a series of number, max(list) will return the max value in the list.
### min(list)
Return the min value in the list.
### turtle.setworldcoordinates(min x, min y, Max x, Max y)
Set the canva sizes to the corresponding min and max x, y value.
(其實概念比較像是整個畫布的像素不變但是單位長度的像素量改變)
### dictionary
#### format
dic = {"key1": value1, "key2": value2, "key3": value3}
E.g.
```
heads = {"David": (589, 106, 48, 63),
"Gibson": (474, 102, 44, 58),
"Jogesh": (438, 146, 45, 60),
"Paul": (522, 162, 55, 68)}
```
#### dic["key"]
Get the value under that key
#### Inserting item
```
dic["newkey"] = new_value
```
#### deleting item
```
del dic["key"]
```
#### printing dictionary
* dic.items(): get both key and value
```
for key, value in dic.items():
print(key, value)
```
* dic.keys(): get the list of keys
```
for key in dic.keys():
print(key)
```
* dic.values():
```
for value in dic.values():
print(value)
```
* in
This is an operator which can be used to find items in the list.
E.g.
`a in x`
returns True if a is in collection x, otherwise False
E.g.
```
heads = {"David": (589, 106, 48, 63),
"Gibson": (474, 102, 44, 58),}
if "Gibson" in heads:
print ("He's there!")
# The program will print
# He's there!
# since there is the key "Ginson" in the dictionary heads.
```
#### A list can't be use as a key in dictionary, but you can use a tuple as a key as an alternative
## 11/16
### class
(恩有點難解釋但應該不至於看不懂?)
就是制定一個class之後你可以給訂一些這個class有的性質(attributes),
然後也可以做一些只有這個class適用的functions(methods)
E.g.
```
class simplesquare:
# __init__() is the constructor
def __init__(self, length)
# self.length is an attribute of the class
self.length = length
# area() is a method of the class simplesquare
def area(self):
return = self.length * self.length
```
#### constructor
* It is a function automatically called when an instance of the class is created
* The attributes of the class are defined here
#### self parameter
* It is required for every method of the class
* It represents the current instance of the class
#### method
It is just like function but it is only applicable for this class
## 11/21
### recursive function
the function which will call itself when executing
## final pastpaper
### open(filename, mode)
* Open or create a text file named "filename"
* mode can be:
* "r" for read only
### if 和 while
* if, while後面的條件
* 如果放True或0以外的數字:會執行
* 如果放False或0:不會執行
### "string"*2
把一個string乘上某個數就是將那個string重複幾遍
E.g.
```
s = "123"
ans = s*2
print (ans) #output 123123, not 246!!!
```
## Final pastpaper questions should be reviewed
* 2020 spring B2 (codeA)
* 2020 fall A8
* 2020 fall B2
* 2020 fall B6
* 2021 fall 11: list[-1:27:-16]是可行的!就是終點在index = 27的物件,然後不會包含他
* 先衝完然後檢查畫畫的 有時間的話把code打到idle跑一遍