0% found this document useful (0 votes)
126 views3 pages

Computer Science Cheat Sheet

The document provides a comprehensive overview of basic Python programming concepts, including syntax for printing, data types, control structures, functions, and libraries like turtle and random. It covers operations with numbers, strings, lists, dictionaries, and the use of loops and conditionals. Additionally, it includes examples of audio editing, event handling, and object-oriented programming with classes.

Uploaded by

ceciwinchad
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
126 views3 pages

Computer Science Cheat Sheet

The document provides a comprehensive overview of basic Python programming concepts, including syntax for printing, data types, control structures, functions, and libraries like turtle and random. It covers operations with numbers, strings, lists, dictionaries, and the use of loops and conditionals. Additionally, it includes examples of audio editing, event handling, and object-oriented programming with classes.

Uploaded by

ceciwinchad
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

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
turtle.color(colours[x+1%4]) # +1 or -1 for a continuous change of either direction
\t ~ Tab, \n ~ Next line, in the quotation marks, \n
text.rstrip()~ 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 = random.randint(1,4) # generating 1, 2 3 or 4 ~ x = random.randint(0,0) # generating 0
beautiful_colours = [‘red’, ‘pink’, ‘blue’] color = random.choice(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 animal.keys(): ~ for value in animal.values():
print(key) ~ print(value)
for key, value in animal.items(): ~ 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
turtle.setworldcoordinates(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
feelings.insert(2, ‘amazed’)
feelings[-1] # counting backward
feelings.remove(‘sad’) ~ feelings.append(‘hungry’) ~ feelings+=(‘hungry’)
this_feeling = feelings[1] ~ feelings[1] = feeling[2] ~ feeling[2] = this_feeling # 做交換
feelings.sort() ~ feelings.reverse()
feelings.count(‘hungry’) → 1, appear once ~ feelings.index(‘scared’) → 0, index number = 0
feelings = ['amazed', 'angry', 'excited', 'happy', 'hungry', 'scared']
feelings[ : : -1] → feelings.reverse ~ 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 value.count(position) > values.count(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
turtle.textinput(‘Title’, ‘prompt’)
turtle.numinput(‘Title’, ‘prompt’, default, min, max)~ float

Text file
my_picture = open(‘this_is_my_file.txt’, ‘w’) # r = reading, # w = writing
mypicture.write(‘Hi, Bitch!’)
line = line.rstrip()
items = line.split(‘\t’)
line = A\tB ~ items = line.split("\t") ~ items = ['A', 'B']

my_picture.close()

Turtle
import turtle # ⽤紙筆畫 turtle.bye() # close window
screen_height, screen_width = 100, 300
turtle.goto(50, 50) ~turtle.home() #goto (0,0)
turtle.down() ~ turtle.up()
turtle.forward(50) ~ turtle.backward()
turtle.width(5)
turtle.right(35) # angle rotating by 35° to the right
turtle.setheading(90) # 90°係向上,270° 係向下
turtle.begin_fill() # use the line when to draw a filled shape ~turtle.end_fill()
turtle.dot(100) # Enter the diameter, same as the pen color, can under turtle.up()
turtle.pencolor( pencolor ) ~ turtle.fillcolor( fillcolor )random
turtle.color(pencolor,fillcolor ) ~ turtle.color(‘red’) # ‘grey’+str(70)
turtle.bgcolor(‘yellow’) ~ turtle.bgpic(‘File name’)
turtle.setup(width, height)
turtle.clear() # delete everything so far
turtle.speed(2) # 0 <= N <= 10, 1 = slow, 10 = fast, 0 = immediately ‘jump’
turtle.circle(250) # Enter the radius, x >0, turn left and tengentially
turtle.hideturtle() ~turtle_name.showturtle()
turtle.write(‘Hello’ + name+ ‘!’, font=(font_type, font_size, font_style)) # use + +
#向下移⼀⾏防⽌重疊
turtle.tracer(True) #same time?

Event Handling
def a(x,y): def b(x,y): def d():
turtle.goto(x,y) turtle.up() turtle.dot(10)
turtle.dot(10) turtle.goto(x,y)cor
turtle.down

turtle.ondrag(a) ~ automatically generate the x and y


turtle.onscreenclick(b) ~ click somewhere in the turtle window
turtle.onkeypress(d,'d') ~ # keys include ‘Up’, ‘Down’, ‘Right’, ‘a’, ‘1’

turtle.listen()

Default Turtle & Additional Turtle


Import turtle ~ newTurtle = turtle.Turtle()
turtle.shape(‘circle’) ~ ‘triangle’ ~ ‘Arrow’ ~ ‘Classic’~ ‘Turtle’
turtle.addshape("ninja.gif")# Only GIF format ~ turtle.shape(‘ninja.gif’) #GIF image
turtle.shapesize(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
newTurtle.done() (remove the original turtle)

Properties: thisTurtle.xcor() thisTurtle.position() ~ heading/ pencolor/ fillcolor/ width/ ycor


0<=turtle.heading<360

Objects
class dog:
def __init__(self, name, colour):
self.name = name
self.colour = colour
def color(self):
return self.colour
def show_color(self):
print('The dog is ',self.colour, 'in color.')
snoopy = dog('SNOOPY', 'White')
snoopy.show_color() → The dog is White in color.
print(snoopy.name) → SNOOPY
color(snoopy) → White

### Fixing the line/ editing the code, CONSIDER THE MARKS!!! ###
# ‘‘‘ ’’’ for comment

You might also like