COMP1021_HKUST@Spring2013
Short Description
This is a summary of all syntax taught in this course, with some extra supplementary syntax of Python. COMP1021 is a cou...
Description
COMP1021: PYTHON SYNTAX BOX Contents Basic Syntax .................................................................................................................................................................................................................................................. 2 Modular programming ................................................................................................................................................................................................................................ 4 Advanced Syntax ........................................................................................................................................................................................................................................ 5 Python – Optimisation .................................................................................................................................................................................................................................. 7 Python – File Handling.................................................................................................................................................................................................................................. 7 Control Statements ...................................................................................................................................................................................................................................... 8 Turtle Functions – Import turtle .................................................................................................................................................................................................................... 8 Turtle Functions – Event Handling ............................................................................................................................................................................................................. 11 Time library – Managing python time ...................................................................................................................................................................................................... 12 Random Library – Import random ............................................................................................................................................................................................................ 12 (External Library) Music Functions – import pygame.midi..................................................................................................................................................................... 12 Initialisation and Closing ........................................................................................................................................................................................................................ 12 L-System (Start value, Replacement rules, …) ........................................................................................................................................................................................ 13 Appendix-Instrument ................................................................................................................................................................................................................................. 14
1
Basic Syntax I/O Functions Conversion Functions
print(‘’, end=’’)
Output a string on the screen (Default: end=eoln) end = End the line with escape char or other (e.g. eoln, null) Convert into
int()
str()
Convert any into
ord()
Return the ASCII code of the char in decimal number system Arithmetic Functions
= input(‘’)
Prompt a string Input a string
round(, ) return
Round the into float number with If not set: Convert into integer If = 0, data type remains unchanged
max ()
chr()
Return the char with specified ordinal value
round(, ) return
Does nothing with even with greater than 0
max ()
Return the max value Return the min value If = : Ordinal value (e.g. ord(‘B’) > ord(‘A’) If … = : max() = max(.keys()), max(.items()) .keys() Return , Comments
‘’’ ‘’’
#
Comments in paragraph length Operators
Comments on a single line
// (Division integer), % (Mod)
+= (a = a + …)
Truncated: 不要小數點後的字 (e.g.) 8.5 % 2 = 0.5 (Modulus operator: No conversion) >>> 2.0000000000000001 == 2 True >>> 2.000000000000001 == 2 False >>> type(2/2) >>> type(2//2)
Shorthand Assignment ( = )
Comparison Operator
==, !=, >=, , != == Comparison operator
True or || > 0 (Non-zero)
False or = 0
break Current
not and or Logical operator
continue
Loop Structure
Current Loop
Current Iteration
Loop Structure
Next Iteration
iteration
”continue” Statement of Current Loop Structure
Swapping
, , …= , , … Assign the nth value of the list on the right to the nth item of the list on the left ( s can be of different types
)
= [ : : -1] As = -1, not specified = -1, not specified = Error Reporting
Try
import sys #Recognise System Error
Process
cases
try:
Programme
except
except :
Exception
Error:
ValueError
I/O error
Datatype
Error
else: Reminder
Quotes in Python can be “ (Double quote) or ‘ (Single quote) They must be in pair Indentation Indentation takes over any structural brackets Indentation wrong Syntax Error
All { (Big bracket) or ; (Semi-colon) Replaced by indentation in Python
Range 或 List 的 Step 定奪【沒提供】的 start or end 的 Value Positive Step: start = 0 , end = len() Negative Step: start = ord(last item), end =
Pressing
Kill the program in a friendly way
3
Modular programming Defining functions
def (, , …):
return Return a value and Variables:
Define your own function,
parameters
Procedure
Define Global vs. Local Class and objects
Define the Class Name. All included function can be called by .
def __init__ (self, , ):
Define the initial parameters that new class objects have to provide 1st self
def (self, , …) Functions
__init__
Variables
Local variable is limited to functions
class :
Class
Function
= ‘’
can be used outside modules
1st
Function
localized 的 Global Variable vs. Local variable
global
Define Function
end
self. =
self
variables
self.
Call
(@Class)
variables
= (, , …) Define new object as a member of the class
4
Instance Objects (Attribute Reference) (Class obj.) Method Objects ( )
Property (
)
Advanced Syntax Range (List) (Array)
range(, , )
list(range(0, 3)) == 0, 1, 2 3-1
A temporary list consisting integers from to Step: +1 +
range(, , )
range(, ) Range from to - 1
Range from large to small, with negative step [int_h]
(e.g. of ): ’funny’[-1:2:] == ‘’
[int_l-1]
[, , …]
e.g. p == ape[1] String is a list of characters
= [, ,…]
= (, ,…)
Items can be in different types Enclosed by a pair of square brackets Can be modified positive ordinal value: from 0 from left [0]: Leftmost item List (Functions)
’funny’[2:-1:] == ‘nn’
character == []
Self-defined set starting with item 0 (ordinal value == 0) List and tuple
‘funny’[-1:2:-1] == ‘yn’
Items can be in different types Enclosed by a pair of normal brackets Cannot be modified (Constant list) negative ordinal value: from -1 from right [-1]: Rightmost item
.insert(, )
.remove () Remove the from
String
Insert an into the of the
[::]
.append() Append an to the
: remains unchanged Output an modified with specified features
.index()
= .pop()
Return the position of the in the list
Remove the last item in the list and contain with 5
如果沒有的話,Return: “ is not in the list Dictionary = List type with (not only automatically assigned integer) (When calling them, the order of all items are rearranged)
Nested List (record) (3D structure) String Tuple List Tuple
Default = len() - 1
= { : , : , …}
for key, value in .items(): print(key, value)
[] =
Print out
()
.items()
.values()
dict_items([(, ), (, ), …])
dict_values([, , …]) Assessing Items
del []
.keys()
Delete the item (key and value) with del : Can be used for any : Remove its memory location
dict_keys([, , , …])
[x_axis][y_axis][z_axis] Excel
Database
line by line
Record
2D Structure 3D Structure
Surface Cube
Datum Datum
[::]
len() Return the length of the list = ord([-1]) + 1
(e.g.) ‘funny’[1:3] == ‘un’ (Not ‘unn’ ) Default: == 0, == len(string_type>),反正是最後 一個 char
char
+
*
copies of : 重複而已 (e.g.) ‘fun’ * 3 == ‘funfunfun’
Text concatenation: (e.g.) ‘fun’ + ‘kid’ == ‘funkid’
6
Python – Optimisation Turtle library
turtle.undo()
turtle.setundobuffer()
Undo the previous turtle process Improt sys
sys.getrecursionlimit()
can be
Return the size of the stack for python
None
:
undo buffer
sys.setrecursionlimit()
Set the size of the stack to Stack ……
Python – File Handling Escape characters Read & Write files
\t
Tab character
\n
New line character
= open(‘’, ‘r’) ‘r’: Open the file as Read-Only Mode
= open(‘’, ‘’) ‘w’: Open the file as Write Mode ‘wt’: Open the file using write + text mode Whenever the file is opened this way, everything in the file is cleared.
.write()
.close()
Write the to the : Will be in
_io.TextIOWrapper
for line in : .readlines() Remove char (String )
list
class (not str class)
statement
Lines
[] items
Default = space character .strip
.strip(‘’)
String
Free up System resources
.lstrip(‘’)
= .split(‘’)
Slice at all positions of Create a
7
.rstrip(‘’))
Control Statements If Statement
if :
elif :
If condition if true, run the process
else:
一定要有 If Statemtn 在前(廢話)If … else if … else … While Loop
while : Condition == True,
For Loop
”break” or
condition == False
for in :
_
variable (e.g.) for _ in range(10):
Integer or character = List items,
List
ordinal item
Turtle Functions – Import turtle (usr_turtle:User-defined turtle)(turtle: System turtle, with all attributes accessible) Basic
Import turtle
Import the turtle library for use Movement
usr_turtle.goto(, )
usr_turtle.reset()
Initialise the turtle on the screen
usr_turtle.forward() Move the turtle ahead of its present direction
turtle.done()
Stop the turtle from further intruption
usr_turtle.backward()
Move the turtle back to the direction if its tail
usr_turtle.setpos(, )
Initial position (middle) = 0, 0 Move the turtle to a specific coordinate on the screen
usr_turtle.left()
Rotate the turtle leftward by degrees Drawing
usr_turtle.width()
usr_turtle.right()
Rotate the turtle rightward by degrees
usr_turtle.up() 8
usr_turtle.speed() 0: Instant ; 1: Slow < 10: Fast
usr_turtle.down()
Put down the turtle Draw when moving
Set the width of lines drawn by turtle in pixels
Take up the turtle Not drawing when moving
turtle.begin_fill()
usr_turtle.fillcolor()
Set fill colour in colour
turtle.end_fill()
Fill the shape drawn by the turtle with fill colour
usr_turtle.fillcolor()
usr_turtle.color() Set colour for both fill colour and pen colour
usr_turtle.color(, )
Return the present fill color
Set colour for 2 types of colours
usr_turtle.undo() Undo the previous step as stored in the turtle stack
usr_turtle.color() pen colour and fill colour
usr_turtle.dot(, )
usr_turtle.write(, align=””, font = (“”, “”)
Define the dot size and drop a dot Geometry
Write on with the 1st char of on turtle
usr_turtle.circle(, ) Draw a circle with radius specified and centre at from the left of the usr_turtle. : +ve: Centre on the left; -ve: Centre on the right Counterclockwise ( > 0) Draw with . A complete circle is 360
Turtle Screen Control
turtle.update() Update the turtle screen To be used after usr_turtle.tracer(False)
usr_turtle.clear()
usr_turtle.tracer(True):
turtle.bgcolor()
Set the background colour of turtle screen
usr_turtle.hideturtle()
Clear the drawings from , not other turtles
turtle.tracer () usr_turtle.tracer(False):
.
usr_turtle.showturtle() Turtle
turtle.colormode(1.0) 1.0
: Float type,
255
Set colour attributes into format
turtle.colormode(255)
: Integer Type
Set colour attributes into
0.0 ~ 1.0
Turtle name
Color attribute Assign
turtle.bgpic(‘’)
Set the background image to the 9
0 ~ 255 format Color
Turtle system settings
turtle.mode(‘world’) / turtle.mode(‘standard’)
Use the self-defined world or standard for turtle
turtle.setup(width=, height=)
Setup the turtle screen size. For , it means the % of the OS screen occupied by this turtle screen
turtle.setworldcoordinates(, , , )
Define the coordinates of the new world Recurring functions Define new turtles
turtle.ontimer(, )
Recur the function per infinitely
usr_turtle.shape (‘’)
Predefined shapes: Arrow, Turtle, Circle, Square, Triangle, Classic
turtle.addshape (‘’) User defined shape can be used only after addshape
usr_turtle.shapesize(‘’, ‘’) Define the turtle size with heights and width
= turtle.Turtle() Define new turtle with name =
= [] .append(turtle.Turtle())
Make good use of append(), instead of predefining the amount of list items (e.g.) turtles[i] = usr_turtle.Turtle()
10
Turtle Functions – Event Handling usr_turtle.on (Mouse movement) No brackets after (i.e. (),
usr_turtle.onclick ()
Run the when the turtle in clicked by mouse
usr_turtle.ondrag () Run the when users drags the turtle
Move the turtle according to your mouse movement For instant update of the position, need usr_turtle.tracer(False) + usr_turtle.update()
usr_turtle.xcor()
usr_turtle.ycor() Return the y coordinate of the turtle
turtle.onscreenclick ()
Run the when the screen is clicked by mouse
turtle.onkeypress (, ‘’)
turtle.onkeyrelease(, ‘’) Run the Run the when the is released
turtle.listen() Keep listening any keyboard event Run this like usr_turtle.done(), must-have +
Run the when the is pressed All turtle.on + Related to
Run the according to the timer
usr_turtle.ondrag (usr_turtle.goto)
Return the x coordinate of the turtle usr_turtle.on (KB, MOUSE, clicking)
turtle.ontimer (, )
: Requires def (null_x, null_y)
11
Program
Time library – Managing python time Time halt
Condition: Used for delay in pressing/ leaving on/from a note Smooth
time.sleep()
Wait for seconds to next statement Python uptime
time.clock()
Return the uptime of python, in second starting from 0
time.clock() >>> 6.182458438486231 Program
Random Library – Import random Randomise data
random.randrange(, )
random.randint(, ))
Generate integers between int_l and int_h Shuffling list
Randomise an integer between (Inclusive) integer_l and integer_h
random.shuffle()
random.uniform(
View more...
Comments