1
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
2
Basic Syntax
I/OFunctions
print(‘<str_type>’, end=’<escape_char>’)
Output a string on the screen (Default: end=eoln)end = End the line with escape char or other (e.g. eoln, null)
<str_type> = input(‘<string>’)
Prompt a string Input a string Conversion
Functions
int(<string>)
Convert <string> into <integer> Convert any <simple data type> into <string>
str(<integer/float>)
ord(<character>)
Return the ASCII code of the char in decimal number system Return the char with specified ordinal value
chr(<ordinal_value>)
ArithmeticFunctions
round(<float/integer_type>, <n_decimal_places>)
return <float_type>
Round the <float_type> into float number with <n_decimal_places>
If <decimal_places> not set: Convert into integer If <decimal_places> = 0, data type remains unchanged
round(<integer_type>, <n…>)
return <integer_type>
Does nothing with <integer_type> even with <n…> greater than 0
max (<any_data_type>)
Return the max value Return the min value
max (<any_data_type>)
If <any_data_type> = <list/string/dictionary>: Ordinal value (e.g. ord(‘B’) > ord(‘A’)
If … = <dict_type>: max(<dict_type>) = max(<dict_type>.keys()),
max(<dict_type>.items()) <dict_type>.keys() Return <key>, <value>
Comments
‘’’ <anything_with_eoln_char> ‘’’
Comments in paragraph length Comments on a single line
# <anything_in_single_line>
Operators
+= (a = a + …)
Shorthand Assignment ( <operator>= ) Truncated: 不要小數點後的字
// (Division integer), % (Mod)
(e.g.) 8.5 % 2 = 0.5 (Modulus operator: No conversion)
==, !=, >=, <=, >, <, not
Comparison Operator >>> 2.0000000000000001 == 2 True >>> 2.000000000000001 == 2 False >>> type(2/2) <class ‘float’> >>> type(2//2) <class ‘int’>
3 Precedence
(dec) () Bracket Power Unary operator Multiple operator Arithmetic operator Comparison operator Logical operator ** - * / % // + - < <= => > != == not and or True/ False
True or |<value>| > 0 (
Non-zero
)
False or <value> = 0
Break and Continue Statement
break
Current Loop Structure Current Loop
Loop Structure
continue
Current Iteration Next Iteration iteration ”continue” Statement of
Current Loop Structure
Swapping
<item_1>, <item_2>, …= <item_n>, <item_2>, …
Assign the nth value of the list on the right to the nth item of the list on the left ( ) <item>s can be of different types
<list_type_new> = <list_type_old>[ : : -1]
As <step> = -1, <start_pos> not specified = -1, <end_pos> not specified = Error
Reporting
import sys
#Recognise System Error
try:
<indent> <process>
except <Error>: <process>
else: <process>
Try Process Exception
cases Programme
except Error:
ValueError Datatype Error
I/O error
Reminder Quotes in Python can be “ (Double quote) or ‘ (Single quote)
They must be in pair All Replaced by indentation in Python { (Big bracket) or ; (Semi-colon) Indentation
Indentation takes over any structural brackets Indentation wrong Syntax Error
Range 或 List 的 Step 定奪【沒提供】的
start or end 的 Value
Positive Step: start = 0 , end = len(<list_type>) Negative Step: start = ord(last item), end =
Pressing <Crtl+C>
4
Modular programming
Definingfunctions
def <function_name> (<para_1>,
<para_2>, …):
<processes>
Define your own function, parameters Procedure Define
return <value/nothing>
Return a value and end Function
Variables: Function Variables
localized 的
Global Variable vs. Local variable
Global vs.
Local
global <global_variable>
<global_variable> can be used outside modules Local variable is limited to functions
<local_variable> = ‘’
Classand objects
class <class_name>:
Define the Class Name.
All included function can be called by <class_name>.<fx>
def __init__ (self, <param_1>, <param_2>):
Define the initial parameters that new class objects have to provide
1st self
def <fx> (self, <param_1>, …)
Define Function 1st self
Class Functions __init__ variables
self.<var_name_n> = <param_n>
variables self.<var_name_n> Call (@Class)
<new_obj> = <class_name>(<param_1>,
<param_2>, …)
Define new object as a member of the <class_name> class
Instance Objects (Attribute Reference) (Class obj.)
Method Objects ( )
5
Advanced Syntax
Range (List) (Array)range(<int_l>, <int_h+1>,
<pos_step >)
A temporary list consisting integers from <int_l> to <int_h> Step: +1 + <int_h+1> <int_l>
list(range(0, 3)) == 0, 1, 2
3 - 1range(<int_h>, <int_l-1>,
<neg_step>)
Range from large to small, with negative step <neg_step> <list_type>[int_h] <list_type>[int_l-1]
range(<int_1>, <int_2>)
Range from <int_1> to <int_2> - 1
(e.g. of <neg_step>): ‘funny’[-1:2:-1] == ‘yn’
’funny’[-1:2:] == ‘’ ’funny’[2:-1:] == ‘nn’
[<item_0>, <item_1>, …]
Self-defined set starting with item 0 (ordinal value == 0) e.g. p == ape[1]
character == <str_type>[<ord_value>]
String is a list of charactersList and tuple
<list_type>= [<item_1>, <item_2>,…]
Items can be in different types
Enclosed by a pair of square brackets Can be modified
<tuple_type>= (<item_1>, <item_2>,…)
Items can be in different types
Enclosed by a pair of normal brackets Cannot be modified (Constant list) positive ordinal value: from 0 from left
<list_type>[0]: Leftmost item
negative ordinal value: from -1 from right
<list_type>[-1]: Rightmost item List
(Functions)
<list_type>.insert(<integer_position>,
<item>)
Insert an <item> into the <position> of the <list_type>
<list_type>.remove (<existing_item>)
Remove the <existing_item> from <list_type> String
<list_type>.append(<item>)
Append an <item> to the <list_type> <end_pos+1>:
<list/string_type>[<start_pos>
:
<end_pos+1>
:
<step>]
<list_type> remains unchangedOutput an modified <list_type> with specified features
<list_type>.index(<search_item>)
6
如果沒有的話,Return: “ <search_item> is not in the list Default <index> = len(<list_type>) - 1
Dictionary = List type with <whatever_key> (not only automatically assigned integer) (When calling them, the order of all items are rearranged)
<dict_type> = {<key_1> : <value_1>,
<key_2> : <value_2>, …}
<dict_type>[<key_n>] = <value_n> <key_n>
for key, value in <dick_type>.items():
print(key, value)
Print out <key_n> (<value_n>) line by line
<dict_type>.items()
dict_items([(<key_1>, <value_1>), (<key_2>, <value_2>), …])
<dict_type>.values()
dict_values([<value_1>, <value_2>, …])
del <dict_type>[<key_n>]
Delete the item (key and value) with <key_n>
del : Can be used for any <data_type>: Remove its memory location
Assessing Items
<dict_type>.keys()
dict_keys([<key_1>, <key_2>, <key_3>, …]) Nested List
(record) (3D structure)
<list_type>[x_axis][y_axis][z_axis]
Excel Database Record
2D Structure Surface Datum
3D Structure Cube Datum
String
Tuple List Tuple
char
len(<list_type>)
Return the length of the list = ord(<list_type>[-1]) + 1 (e.g.) ‘funny’[1:3] == ‘un’
<str_type>[<start_pos>
(Not ‘unn’:
<end_pos+1>
):
<step>]
Default: <start_pos> == 0, <end_pos+1> == len(string_type>),反正是最後 一個char
<string_type_1> + <string_type_2>
Text concatenation:
(e.g.) ‘fun’ + ‘kid’ == ‘funkid’
<string_type_1> * <integer>
<integer> copies of <string_type_1>: 重複而已 (e.g.) ‘fun’ * 3 == ‘funfunfun’
7
Python – Optimisation
Turtle libraryturtle.undo()
Undo the previous turtle process <integer_type> can be
turtle.setundobuffer(<integer_type>)
None : undo buffer Improt syssys.getrecursionlimit()
Return the size of the stack for python Set the size of the stack to <integer_type>
sys.setrecursionlimit(<integer_type>)
Stack ……
Python – File Handling
Escapecharacters
\t
Tab character New line character
\n
Read &
Write files
<file_var> = open(‘<filename>’, ‘r’)
‘r’: Open the <filename> file as Read-Only Mode ‘w’: Open the <filename> file as
<file_var> = open(‘<filename>’, ‘<w or wt>’)
Write Mode‘wt’: Open the file using write + text mode
Whenever the file is opened this way, everything in the file is cleared.
<file_var>.write(<str_type>)
Write the <str_type> to the <file_var> Free up System resources
<file_var>.close()
<file_var>: Will be in _io.TextIOWrapper class (not str class)
for line in <file_var>: statement <file_var> <file_var>[<int>] <file_var>.readlines() Lines <list_type> items
Remove char (String
)
Default <char> = space character
.<l or n or …>strip <str_type>
<str_type>.strip(‘<char>’)
<str_type> <char><str_type>.lstrip(‘<char>’)
<str_type> <char><str_type>.rstrip(‘<char>’))
<str_type> <char> String8
Control Statements
If Statementif <condition_true> : <process>
If condition if true, run the process
elif <condition_true>: <process>
else: <process>
一定要有If Statemtn 在前(廢話)If … else if … else … While Loop
while <condition_true>: <process>
Condition == True, ”break” or condition == False
For Loop
for <simp_data_type> in <list>: <process>
<simp_data_type> _ 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 Initialise the turtle on the screen
usr_turtle.reset()
Stop the turtle from further intruptionturtle.done()
Movementusr_turtle.goto(<x_coor
>, <y_coor>)
usr_turtle.setpos(<x_co
or>, <y_coor>)
Initial position (middle) = 0, 0
Move the turtle to a specific coordinate on the screen
usr_turtle.forward(<pixels>)
Move the turtle ahead of its present direction
usr_turtle.backward(<pixe
ls>)
Move the turtle back to the direction if its tailusr_turtle.left(<angle>)
Rotate the turtle leftward by <angle> degrees
usr_turtle.right(<angle>)
Rotate the turtle rightward by <angle> degrees
usr_turtle.speed(<speed_i
ndex>)
0: Instant ; 1: Slow < 10: Fast Drawing
usr_turtle.width(<width
9 Set the width of lines drawn by turtle in
pixels Take up the turtle Not drawing when moving
turtle.begin_fill()
<Start drawing>
turtle.end_fill()
Fill the shape drawn by the turtle with fill colour
usr_turtle.fillcolor(<hex/na
me>)
Set fill colour in <hex/name> colour
usr_turtle.fillcolor()
Return the present fill color
usr_turtle.color(<both_col
or>)
Set colour for both fill colour and pen colour
usr_turtle.color(<pen_col
or>, <fill_color>)
Set colour for 2 types of colours
usr_turtle.color()
pen colour and fill colour
usr_turtle.undo()
Undo the previous step as stored in the turtle stack
usr_turtle.dot(<integer_diameter>,
<colour>)
Define the dot size and drop a dot
usr_turtle.write(<str_type>, align=”<left/right/center>”,
font = (“<font_name>”, “<normal/bold/italic>”)
Write <str_type> on with the 1st char of <str_type> on turtle
Geometry
usr_turtle.circle(<radius>, <angle_of_arc>)
Draw a circle with radius specified and centre at <radius> from the left of the usr_turtle.
<radius>: +ve: Centre on the left; -ve: Centre on the right
Counterclockwise ( <angle_of_arc> > 0)
Draw with <angle_of_arc>. 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()
Clear the drawings from <turtle>, not other turtles
usr_turtle.hideturtle()
usr_turtle.showturtle()
Turtleturtle.tracer (<Boolean>)
usr_turtle.tracer(False): usr_turtle.tracer(True):turtle.colormode(1.0)
1.0 : Float type, 255 : Integer Type
Set colour attributes into 0.0 ~ 1.0 format
turtle.colormode(255)
Set colour attributes into 0 ~ 255 format
Turtle Color attribute Color name Assign
turtle.bgcolor()
10 Turtle system
settings
turtle.mode(‘world’) /
turtle.mode(‘standard’)
Use the self-defined world or standard for turtle
turtle.setup(width=<screen_% or pixel>,
height=<screen_% or pixel>)
Setup the turtle screen size. For <screen%>, it means the % of the OS screen occupied by this turtle screen
turtle.setworldcoordinates(<left>, <bottom>, <right>, <top>)
Define the coordinates of the new world Recurring
functions
turtle.ontimer(<function>, <time_in_millisecond>)
Recur the function per <time_in_millisecond> infinitely Define new
turtles
usr_turtle.shape
(‘<Shape_name>’)
Predefined shapes: Arrow, Turtle, Circle, Square, Triangle, Classic
turtle.addshape
(‘<gif_image_file>’)
User defined shape can be used only after
addshape
<New_turtle> =
turtle.Turtle()
Define new turtle with name = <New_turtle>
usr_turtle.shapesize(‘<hei
ght>’, ‘<width>’)
Define the turtle size with heights and width
<turtles_list_type> = []
<turtles_list_type>.append(
turtle.Turtle()
)
Make good use of append(), instead of predefining the amount of list items (e.g.) turtles[i] = usr_turtle.Turtle()
11
Turtle Functions – Event Handling
usr_turtle.on (Mouse movement) No brackets after <event_function> (i.e. <…>(),usr_turtle.onclick (<event_function>)
Run the <event_function> when the turtle in clicked by mouse
turtle.ontimer (<event_function>,
<timer_millisecond>)
Run the <event_function> according to the timer
usr_turtle.ondrag (<event_function>)
Run the <event_function> when users drags the turtle Move the turtle according to your mouse movement
usr_turtle.ondrag (usr_turtle.goto)
For instant update of the position, need usr_turtle.tracer(False) + usr_turtle.update()
usr_turtle.xcor()
Return the x coordinate of the turtle Return the y coordinate of the turtle
usr_turtle.ycor()
usr_turtle.on(KB, MOUSE, clicking)
turtle.onscreenclick (<event_function>)
Run the <event_function> when the screen is clicked by mouse
turtle.onkeyrelease(<event_function>,
‘<key>’)
Run the Run the <event_function> when the <key> is released
turtle.onkeypress (<event_function>,
‘<key>’)
Run the <event_function> when the <key> is pressed
turtle.listen()
Keep listening any keyboard event
Run this like usr_turtle.done(), must-have + Program All turtle.on <event_function> + Related to : Requires def <event_function_name> (null_x, null_y)
12
Time library – Managing python time
Time halttime.sleep(<time_in_second>)
Wait for <time_in_second> seconds to next statement
Condition: Used for delay in pressing/ leaving on/from a note Smooth
Python uptime
time.clock()
Return the uptime of python, in <float_type> second starting from 0
time.clock()
>>> 6.182458438486231 Program
Random Library – Import random
Randomise datarandom.randrange(<int_l>, <int_h+1>)
Generate integers between int_l and int_h Randomise an integer between (Inclusive) integer_l and integer_h
random.randint(<int_l>, <int_h>))
Shuffling listrandom.shuffle(<list_type>)
Randomise the orders of all <list_type> items Randomise a float number
random.uniform(<low, <high>)
between <low> and <high> (not inclusive)(External Library) Music Functions – import pygame.midi
Initialisation and Closing
Import the midi module for playing music
import pygame.midi
Import the time module for time control
import time
Initialise the MIDI (playing music) module
pygame.midi.init()
Create an output to play music
output = pygame.midi.Output(
pygame.midi.get_default_output_id()
)
Close Music output
output.close()
Close the MIDI module
13 Note On/
Off
output.note_on(<pitch>, <volume>, <channel>)
Drum Channel <pitch> <instrument>
output.note_off(<pitch>, <volume>,
<channel>)
Pitch, Volume, ChannelPitch in range(128)
Note in range(24, 108)Channel in
range(16)
Default<channel> 0 Drum <channel> 9Volume in range(128)
127: (For <channel> == 0)output.set_intstrument(<instrument_code>)
Instrument code in range (0, 127)
L-System (Start value, Replacement rules, …)
ExplanationVariables = { F }
Variables that have replacement rules F: Usually represents “forward”
Constant = {+, - }
Constant that have predefined command
+: Turn left, -: Turn right
Starting string = FX+F
Initial string from further replacement Rules to replace the command char in string
Rules = F FF-F-F++
Angle = 90
14
Appendix-Instrument
0 Acoustic GrandPiano 8 Celesta 16 Drawbar Organ 24 Acoustic Guitar (nylon) 32 Acoustic Bass 40 Violin
1 Bright Acoustic Piano 9 Glockenspiel 17 Percussive Organ 25 Acoustic Guitar (steel) 33 Electric Bass (finger) 41 Viola 2 Electric Grand
Piano 10 Music Box 18 Rock Organ 26 Electric Guitar (jazz) 34 Electric Bass (pick) 42 Cello 3 Honky-tonk Piano 11 Vibraphone 19 Church Organ 27 Electric Guitar
(clean)
35 Fretless Bass 43 Contrabass
4 Electric Piano 1 12 Marimba 20 Reed Organ 28 Electric Guitar
(muted) 36 Slap Bass 1 44 Tremolo Strings
5 Electric Piano 2 13 Xylophone 21 Accordion 29 Overdriven Guitar 37 Slap Bass 2 45 Pizzicato Strings
6 Harpsichord 14 Tubular Bells 22 Harmonica 30 Distortion Guitar 38 Synth Bass 1 46 Orchestral Harp
7 Clavinet 15 Dulcimer 23 Tango
Accordion 31 Guitar Harmonics 39 Synth Bass 2 47 Timpani
48 String Ensemble 1 56 Trumpet 64 Soprano Sax 72 Piccolo 80 Lead 1 (square) 88 Pad 1 (new
age)
49 String Ensemble 2 57 Trombone 65 Alto Sax 73 Flute 81 Lead 2 (sawtooth) 89 Pad 2 (warm)
50 Synth Strings 1 58 Tuba 66 Tenor Sax 74 Recorder 82 Lead 3 (calliope) 90 Pad 3
(polysynth)
51 Synth Strings 2 59 Muted
Trumpet 67 Baritone Sax 75 Pan Flute 83 Lead 4 (chiff) 91 Pad 4 (choir)
52 Choir Aahs 60 French Horn 68 Oboe 76 Blown Bottle 84 Lead 5 (charang) 92 Pad 5 (bowed)
53 Voice Oohs 61 Brass Section 69 English Horn 77 Shakuhachi 85 Lead 6 (voice) 93 Pad 6 (metallic)
54 Synth Choir 62 Synth Brass 1 70 Bassoon 78 Whistle 86 Lead 7 (fifths) 94 Pad 7 (halo)
55 Orchestra Hit 63 Synth Brass 2 71 Clarinet 79 Ocarina 87 Lead 8 (bass +
lead)
95 Pad 8 (sweep)
96 FX 1 (rain) 104 Sitar 112 Tinkle Bell 120 Guitar Fret Noise
97 FX 2 (soundtrack) 105 Banjo 113 Agogo 121 Breath Noise
98 FX 3 (crystal) 106 Shamisen 114 Steel Drums 122 Seashore
99 FX 4 (atmosphere) 107 Koto 115 Woodblock 123 Bird Tweet
100 FX 5 (brightness) 108 Kalimba 116 Taiko Drum 124 Telephone Ring 101 FX 6 (goblins) 109 Bagpipe 117 Melodic Tom 125 Helicopter
102 FX 7 (echoes) 110 Fiddle 118 Synth Drum 126 Applause