Professional Documents
Culture Documents
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
Basic Syntax
I/O Functions Conversion Functions Output a string on the screen (Default: end=eoln) end = End the line with escape char or other (e.g. eoln, null) Convert <string> into <integer>
print(<str_type>, end=<escape_char>)
<str_type> = input(<string>)
int(<string>)
Convert any <simple data type> into <string> Return the char with specified ordinal value
str(<integer/float>)
Return the ASCII code of the char in decimal number system Arithmetic Functions
ord(<character>)
chr(<ordinal_value>)
round(<float/integer_type>, <n_decimal_places>)
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>)
Does nothing with <integer_type> even with <n> greater than 0
return <float_type>
return <integer_type>
Return the max value Return the min value 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 Operators Comments in paragraph length
max (<any_data_type>)
max (<any_data_type>)
<anything_with_eoln_char> += (a = a + )
# <anything_in_single_line>
Comparison Operator
Truncated: (e.g.) 8.5 % 2 = 0.5 (Modulus operator: No conversion) >>> 2.0000000000000001 == 2 True >>> 2.000000000000001 == 2 False >>> type(2/2) <class float> >>> type(2//2) <class int> 2
() Bracket
** Power
Unary operator
* / % // Multiple operator
+Arithmetic operator
Swapping
import sys #Recognise System Error try: <indent> <process> except <Error>: <process> else: <process>
Exception
Error
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 Kill the program in a friendly way
Pressing <Crtl+C>
3
Modular programming
Defining functions
return <value/nothing>
Return a value and Variables: localized Global Variable vs. Local variable end Function Function Variables
global <global_variable>
<global_variable> can be used outside modules Define the Class Name. All included function can be called by <class_name>.<fx>
<local_variable> =
Local variable is limited to functions Define the initial parameters that new class objects have to provide 1st self
class <class_name>:
self.<var_name_n> = <param_n>
variables self.<var_name_n> Call
Advanced Syntax
Range (List) (Array)
list(range(0, 3)) == 0, 1, 2
3-1
range(<int_1>, <int_2>)
Range from <int_1> to <int_2> - 1 (e.g. of <neg_step>): funny[-1:2:] == funny[-1:2:-1] == yn funny[2:-1:] == nn
[<item_0>, <item_1>, ]
character == <str_type>[<ord_value>]
e.g. p == ape[1] String is a list of characters 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 <list_type>[-1]: Rightmost item
Items can be in different types Enclosed by a pair of square brackets Can be modified positive ordinal value: from 0 from left <list_type>[0]: Leftmost 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>
<list/string_type>[<start_pos>:<end_pos+1>:<step>]
<end_pos+1>: <list_type> remains unchanged Output an modified <list_type> with specified features Remove the last item in the list and contain with <container> 5
<list_type>.index(<search_item>)
<container> = <list_type>.pop(<index>)
Return: <search_item> is not in the list Dictionary = List type with <whatever_key> (not only automatically assigned integer) (When calling them, the order of all items are rearranged)
<dict_type>.items()
dict_items([(<key_1>, <value_1>), (<key_2>, <value_2>), ]) 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>.values()
dict_values([<value_1>, <value_2>, ])
del <dict_type>[<key_n>]
<dict_type>.keys()
dict_keys([<key_1>, <key_2>, <key_3>, ]) 2D Structure 3D Structure Surface Cube Datum Datum
Nested List (record) (3D structure) String Tuple List Tuple char
<list_type>[x_axis][y_axis][z_axis]
Excel Database Record
len(<list_type>)
Return the length of the list = ord(<list_type>[-1]) + 1
<str_type>[<start_pos>:<end_pos+1>:<step>]
(e.g.) funny[1:3] == un (Not unn ) Default: <start_pos> == 0, <end_pos+1> == len(string_type>) char <integer> copies of <string_type_1>: (e.g.) fun * 3 == funfunfun
<string_type_1> + <string_type_2>
Text concatenation: (e.g.) fun + kid == funkid
<string_type_1> * <integer>
Python Optimisation
Turtle library Undo the previous turtle process Improt sys
turtle.undo()
turtle.setundobuffer(<integer_type>)
<integer_type> can be None : undo buffer
sys.getrecursionlimit()
sys.setrecursionlimit(<integer_type>)
\t
\n
<file_var> = open(<filename>, r)
r: Open the <filename> file as Read-Only Mode
Write the <str_type> to the <file_var> <file_var>: Will be in for line in <file_var>: <file_var>.readlines() Remove char (String ) String list
<file_var>.write(<str_type>)
_io.TextIOWrapper Lines class (not str class) <file_var> <list_type> items
<file_var>.close()
Free up System resources <file_var>[<int>]
statement
<str_type>.strip(<char>)
<str_type> <char>
<str_type>.lstrip(<char>)
<str_type> <char>
<str_type>.rstrip(<char>))
<str_type> <char>
<list_type> = <str_type>.split(<char>)
Control Statements
If Statement If condition if true, run the process While Loop Condition == True, For Loop <simp_data_type>
if <condition_true> : <process>
else: <process>
Import turtle
usr_turtle.reset()
turtle.done()
usr_turtle.forward(<pixels>)
Move the turtle ahead of its present direction
usr_turtle.backward(<pixe ls>)
Initial position (middle) = 0, 0 Move the turtle to a specific coordinate on the screen Rotate the turtle leftward by <angle> degrees Drawing
usr_turtle.left(<angle>)
usr_turtle.right(<angle>)
usr_turtle.speed(<speed_i ndex>)
0: Instant ; 1: Slow < 10: Fast Put down the turtle Draw when moving
usr_turtle.width(<width _in_pixel>)
usr_turtle.up()
8
usr_turtle.down()
usr_turtle.fillcolor(<hex/na me>)
Set fill colour in <hex/name> colour Return the present fill color
usr_turtle.color(<both_col or>)
Set colour for both fill colour and pen colour
turtle.end_fill()
usr_turtle.fillcolor()
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 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.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()
Turtle
turtle.tracer (<Boolean>)
usr_turtle.tracer(False): usr_turtle.tracer(True): 1.0
turtle.colormode(1.0)
: Float type, 255 : Integer Type 0.0 ~ 1.0 Set colour attributes into format Turtle name
turtle.colormode(255)
Set colour attributes into Color attribute Assign 0 ~ 255 format Color
turtle.bgcolor()
turtle.bgpic(<gif_image_file>)
turtle.mode(world) / turtle.mode(standard)
Setup the turtle screen size. For <screen%>, it means the % of the OS screen occupied by this turtle screen
Define the coordinates of the new world Recurring functions Define new turtles
usr_turtle.shape (<Shape_name>)
<New_turtle> = turtle.Turtle()
Define new turtle with name = <New_turtle>
<turtles_list_type> = []
Make good use of append(), instead of predefining the amount of list items (e.g.) turtles[i] = usr_turtle.Turtle()
<turtles_list_type>.append(turtle.Turtle())
10
usr_turtle.onclick (<event_function>)
usr_turtle.ondrag (<event_function>)
Run the <event_function> when users drags the turtle
usr_turtle.ondrag (usr_turtle.goto)
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()
Return the x coordinate of the turtle usr_turtle.on (KB, MOUSE, clicking) Run the <event_function> when the screen is clicked by mouse
usr_turtle.ycor()
Return the y coordinate of the turtle
turtle.onscreenclick (<event_function>)
turtle.onkeyrelease(<event_function>, <key>)
Run the Run the <event_function> when the <key> is released
Run the <event_function> when the <key> is pressed All turtle.on <event_function> + Related to
turtle.listen()
Keep listening any keyboard event Run this like usr_turtle.done(), must-have + : Requires def <event_function_name> (null_x, null_y) Program
11
time.sleep(<time_in_second>) time.clock()
Condition: Used for delay in pressing/ leaving on/from a note Smooth time.clock() >>> 6.182458438486231 Program
Randomise an integer between (Inclusive) integer_l and integer_h Randomise a float number between <low> and <high> (not inclusive)
12
Pitch in range(128)
Note in range(24, 108)
Default <channel> Drum <channel> (For <channel> == 0) Instrument code in range (0, 127)
output.set_intstrument(<instrument_code>)
Variables = { F }
Constant = {+, - }
Rules = F FF-F-F++
Rules to replace the command char in string Number of iterations to be run
Iteration = 4
13
Appendix-Instrument
0 1 2 3 4 5 6 7 48 49 50 51 52 53 54 55 96 97 98 99 100 101 102 103 Acoustic Grand Piano Bright Acoustic Piano Electric Grand Piano Honky-tonk Piano Electric Piano 1 Electric Piano 2 Harpsichord Clavinet String Ensemble 1 String Ensemble 2 Synth Strings 1 Synth Strings 2 Choir Aahs Voice Oohs Synth Choir Orchestra Hit FX 1 (rain) FX 2 (soundtrack) FX 3 (crystal) FX 4 (atmosphere) FX 5 (brightness) FX 6 (goblins) FX 7 (echoes) FX 8 (sci-fi) 8 9 10 11 12 13 14 15 56 57 58 59 60 61 62 63 104 105 106 107 108 109 110 111 Celesta Glockenspiel Music Box Vibraphone Marimba Xylophone Tubular Bells Dulcimer Trumpet Trombone Tuba Muted Trumpet French Horn Brass Section Synth Brass 1 Synth Brass 2 Sitar Banjo Shamisen Koto Kalimba Bagpipe Fiddle Shanai 16 17 18 19 20 21 22 23 64 65 66 67 68 69 70 71 112 113 114 115 116 117 118 119 Drawbar Organ Percussive Organ Rock Organ Church Organ Reed Organ Accordion Harmonica Tango Accordion Soprano Sax Alto Sax Tenor Sax Baritone Sax Oboe English Horn Bassoon Clarinet Tinkle Bell Agogo Steel Drums Woodblock Taiko Drum Melodic Tom Synth Drum Reverse Cymbal 24 25 26 27 28 29 30 31 72 73 74 75 76 77 78 79 120 121 122 123 124 125 126 127 Acoustic Guitar (nylon) Acoustic Guitar (steel) Electric Guitar (jazz) Electric Guitar (clean) Electric Guitar (muted) Overdriven Guitar Distortion Guitar Guitar Harmonics Piccolo Flute Recorder Pan Flute Blown Bottle Shakuhachi Whistle Ocarina Guitar Fret Noise Breath Noise Seashore Bird Tweet Telephone Ring Helicopter Applause Gunshot 32 33 34 35 36 37 38 39 80 81 82 83 84 85 86 87 Acoustic Bass Electric Bass (finger) Electric Bass (pick) Fretless Bass Slap Bass 1 Slap Bass 2 Synth Bass 1 Synth Bass 2 Lead 1 (square) Lead 2 (sawtooth) Lead 3 (calliope) Lead 4 (chiff) Lead 5 (charang) Lead 6 (voice) Lead 7 (fifths) Lead 8 (bass + lead) 40 41 42 43 44 45 46 47 88 89 90 91 92 93 94 95 Violin Viola Cello Contrabass Tremolo Strings Pizzicato Strings Orchestral Harp Timpani Pad 1 (new age) Pad 2 (warm) Pad 3 (polysynth) Pad 4 (choir) Pad 5 (bowed) Pad 6 (metallic) Pad 7 (halo) Pad 8 (sweep)
14