Basic Python
print(‘Hello’) # on the same line
print(‘Hello’, x) ~ print(‘Hello’, x, ‘!’) # x as a variable #
x = input(‘x:’)
‘end =’ ‘\t’ ‘\n’
print(‘1\t2\t3’) → 1 (tab) 2 (tab) 3
print("Hello!\nI am Python!")
Hello! - next line - I am Python!
Numbers
y = round(x) # Gives the nearest even number for N/2, where N is an odd number
Comparison: !=, ==, >, <, <=, >=
Short cuts for operations: +=, -=, *= , /= ,%= , **=, //=
Precedence: ( ),**,[-x, +x],[ *, /, %, //],[ +, -],[ <, >, <=, >=, !=, ==],[ in, not in]
logical precedence: not > and > or
[Link](colours[x+1%4]) # +1 or -1 for a continuous change of either direction
\t ~ Tab, \n ~ Next line, in the quotation marks, \n
[Link]()~ remove anything you can’t see on the right side
Addition # Addition of lists, addition of values
Range
range(1,4) # the range is 1, 2, 3 ~ range(4) # the range is 0, 1, 2, 3
range(0, 12, 3) # the range is 0, 3, 6, 9, not showing 12
print(range(1,4)) → range(1,4)
print(list(range(1,4))) → [1,2,3]
Random
import random # should be place before the ‘if’ clause
x = [Link](1,4) # generating 1, 2 3 or 4 ~ x = [Link](0,0) # generating 0
beautiful_colours = [‘red’, ‘pink’, ‘blue’] color = [Link](beautiful_colours)
if x>0:
print(‘x>0’)
# be aware of where to define the variables
else: ~ elif:
if x: # equivalent to if x!=0:
if x%2: ~ equivalent to ~ for x in range(0,100,2):
Dictionary
animal = {‘狗’: ‘狗叫’, ‘貓’: ‘貓叫’, ‘key’: (‘V0’, ‘V1’)} # OK to use tuples, but not lists
print(animal[‘狗’]) → 狗叫
animal[‘狗’] = ‘污糟’ # change the value or creating new keys
print(animal[key][1]) → V1
del head[‘key’]
for key in [Link](): ~ for value in [Link]():
print(key) ~ print(value)
for key, value in [Link](): ~ for x in animals:
print(key, value) ~ print(x ,animals[x])
# OK for dictionaries in dictionaries
Loops
x = [0, 1, 2, 3] ~ for _ in range(len(x)):
x = 0 ~ while x <=3: ~ x+=1
continue # restart break # break loops
Audio Editing
sample[ : int(len(sample)/2)] # the first half part of the audio
sample[int(len(sample)/2): : -1] # reversing the first half part of the audio
Coordinates
[Link](0, 0, 3, 3) ~ (MinX, MinY, MaxX, MaxY)
String
my_pet = ‘dog’ # A string only contains text, like a tuple, cannot be changed
print(my_pet[1]) → o ~ print(len(my_pet)) → 3
Logic
A or B # 任意條件 AB成立 A and B #條件 AB 同時成立 not A # A 的相反
d = (a and b) or c #必須要條件a 同埋條件 b 成立,或者條件 c 成立 ~ d = a and b or c
d = a and (b or c) #必須要條件a 成立,同埋條件 b 、c 任⼀成立
answer = input(‘Are you ok?’)
condition = answer == ‘ok’ # 當 answer == ‘ok’, condition 成立 ; vice versa
Empty tuple, list, string and 0 = False
while True:
Types of Data
y = int(x) # only integer strings and numbers# 所有同數字有關嘅都要考慮
y = int(float(x)) # for all values ~ print(float(5)) → 5.0
y = str(x) ~ y = bool(x) ~ y = tuple(x)
type(data) → int / bool/ float/ str/ list/ tuple/ dict
if type(x) == str: ~ x = float(x)
List
friend1 = [‘May’, ‘Mary’]; friend2 = [‘Macy’, ‘Mandy’]
All_my_friends = friend1 + friend2 → [‘May’, ‘Mary’, ‘Macy’, ‘Mandy’]
Algebra = [[‘a1’, ‘a2’, ‘a3’], [‘b1’, ‘b2’, ‘b3’]] ~ Algebra[1][2] → ‘b3’
feelings = [‘happy’, ‘sad’, ‘angry’, ‘scared’]
len(feelings) → total number of sequence in the list
for x in range(len(feelings)): ~ print(feelings[x])
feelings[2] = ‘excited’ ~ print(feelings[2][3:]) → ited
[Link](2, ‘amazed’)
feelings[-1] # counting backward
[Link](‘sad’) ~ [Link](‘hungry’) ~ feelings+=(‘hungry’)
this_feeling = feelings[1] ~ feelings[1] = feeling[2] ~ feeling[2] = this_feeling # 做交換
[Link]() ~ [Link]()
[Link](‘hungry’) → 1, appear once ~ [Link](‘scared’) → 0, index number = 0
feelings = ['amazed', 'angry', 'excited', 'happy', 'hungry', 'scared']
feelings[ : : -1] → [Link] ~ feelings[3 : : -1] → Reverse from ‘excited’ to ‘amazed’
feelings[ :5] → ['amazed', 'angry', 'excited', 'happy', 'hungry']; feelings[2: ] → ['excited', 'happy', 'hungry', 'scared']
for position in range(0, len(data)):
if [Link](position) > [Link](mode_value):
mode_value = value[position] ~ find the maximum value of a list
Alphabets = [‘a’, ‘b’] ~ ‘a’ in Alphabets = True # same of tuple, string, dictionary
Function
def function(variable_x, variable_y): ⽤嘅時候要輸入variable/上⾯要定義
def function(x):
y = x*2
z = x+3
return y, z # showing ‘None’ when only ~ return
the_product, the_sum = function(x) # the product = y; the sum = z
print(‘2*x is ’, the_product, ‘and 3+x is’, the_sum)
global variable #定義全域變數,使變數在全域可以使⽤/改變
Input
[Link](‘Title’, ‘prompt’)
[Link](‘Title’, ‘prompt’, default, min, max)~ float
Text file
my_picture = open(‘this_is_my_file.txt’, ‘w’) # r = reading, # w = writing
[Link](‘Hi, Bitch!’)
line = [Link]()
items = [Link](‘\t’)
line = A\tB ~ items = [Link]("\t") ~ items = ['A', 'B']
my_picture.close()
Turtle
import turtle # ⽤紙筆畫 [Link]() # close window
screen_height, screen_width = 100, 300
[Link](50, 50) ~[Link]() #goto (0,0)
[Link]() ~ [Link]()
[Link](50) ~ [Link]()
[Link](5)
[Link](35) # angle rotating by 35° to the right
[Link](90) # 90°係向上,270° 係向下
turtle.begin_fill() # use the line when to draw a filled shape ~turtle.end_fill()
[Link](100) # Enter the diameter, same as the pen color, can under [Link]()
[Link]( pencolor ) ~ [Link]( fillcolor )random
[Link](pencolor,fillcolor ) ~ [Link](‘red’) # ‘grey’+str(70)
[Link](‘yellow’) ~ [Link](‘File name’)
[Link](width, height)
[Link]() # delete everything so far
[Link](2) # 0 <= N <= 10, 1 = slow, 10 = fast, 0 = immediately ‘jump’
[Link](250) # Enter the radius, x >0, turn left and tengentially
[Link]() ~turtle_name.showturtle()
[Link](‘Hello’ + name+ ‘!’, font=(font_type, font_size, font_style)) # use + +
#向下移⼀⾏防⽌重疊
[Link](True) #same time?
Event Handling
def a(x,y): def b(x,y): def d():
[Link](x,y) [Link]() [Link](10)
[Link](10) [Link](x,y)cor
[Link]
[Link](a) ~ automatically generate the x and y
[Link](b) ~ click somewhere in the turtle window
[Link](d,'d') ~ # keys include ‘Up’, ‘Down’, ‘Right’, ‘a’, ‘1’
[Link]()
Default Turtle & Additional Turtle
Import turtle ~ newTurtle = [Link]()
[Link](‘circle’) ~ ‘triangle’ ~ ‘Arrow’ ~ ‘Classic’~ ‘Turtle’
[Link]("[Link]")# Only GIF format ~ [Link](‘[Link]’) #GIF image
[Link](2, 3) ~ Multiply the width by 2; the length by 3, 留意⽅向會變
newTurtle stores variables such as X, Y , θ, color, width, speed. Turtles start in the middle
[Link]() (remove the original turtle)
Properties: [Link]() [Link]() ~ heading/ pencolor/ fillcolor/ width/ ycor
0<=[Link]<360
Objects
class dog:
def __init__(self, name, colour):
[Link] = name
[Link] = colour
def color(self):
return [Link]
def show_color(self):
print('The dog is ',[Link], 'in color.')
snoopy = dog('SNOOPY', 'White')
snoopy.show_color() → The dog is White in color.
print([Link]) → SNOOPY
color(snoopy) → White
### Fixing the line/ editing the code, CONSIDER THE MARKS!!! ###
# ‘‘‘ ’’’ for comment