You are on page 1of 14

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

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>)

Prompt a string Input a string

<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 + )

Comments on a single line

# <anything_in_single_line>

Shorthand Assignment ( <operator>= )

Comparison Operator

==, !=, >=, <=, >, <, not

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

// (Division integer), % (Mod)

Precedence (dec) True/ False Break and Continue Statement

() Bracket

** Power

Unary operator

* / % // Multiple operator

+Arithmetic operator

< <= => > != == Comparison operator

not and or Logical operator

True or |<value>| > 0 (Non-zero) break


Current Loop Structure Current Loop Loop Structure

False or <value> = 0 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 As <step> = -1, <start_pos> not specified = -1, <end_pos> not specified = )

<list_type_new> = <list_type_old>[ : : -1]


Error Reporting

import sys #Recognise System Error try: <indent> <process> except <Error>: <process> else: <process>

Try cases except

Process Programme Error: Datatype ValueError I/O error

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

All { (Big bracket) or ; (Semi-colon) Replaced by indentation in Python

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>
3

Modular programming
Defining functions

def <function_name> (<para_1>, <para_2>, ): <processes>


Define your own function, Define parameters Procedure

return <value/nothing>
Return a value and Variables: localized Global Variable vs. Local variable end Function Function Variables

Global vs. Local Class and objects

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>:

def __init__ (self, <param_1>, <param_2>):

def <fx> (self, <param_1>, )


Define Function Class Functions 1st __init__ self variables (@Class)

self.<var_name_n> = <param_n>
variables self.<var_name_n> Call

<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 ( ) Property ( )

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-1

range(<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] Self-defined set starting with item 0 (ordinal value == 0) List and tuple

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>= [<item_1>, <item_2>,]

<tuple_type>= (<item_1>, <item_2>,)

<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

Return the position of the <search_item> in the list

<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)

Default <index> = len(<list_type>) - 1

<dict_type> = {<key_1> : <value_1>, <key_2> : <value_2>, }


<dict_type>[<key_n>] = <value_n> <key_n> Print out

for key, value in <dick_type>.items(): print(key, value)


<key_n> (<value_n>) line by line

<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

Return the size of the stack for python

sys.getrecursionlimit()

Set the size of the stack to <integer_type> Stack

sys.setrecursionlimit(<integer_type>)

Python File Handling


Escape characters Read & Write files Tab character

\t

New line character

\n

<file_var> = open(<filename>, r)
r: Open the <filename> file as Read-Only Mode

<file_var> = open(<filename>, <w or wt>)


w: Open the <filename> 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 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

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>

Slice at all <char> positions of <str_type> Create a <list_type>

<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>

elif <condition_true>: <process>


If Statemtn If else if else

else: <process>

while <condition_true>: <process>


break or condition == False

for <simp_data_type> in <list>: <process>


_ variable (e.g.) for _ in range(10): List ordinal item Integer or character = List items,

Turtle Functions Import turtle


(usr_turtle:User-defined turtle)(turtle: System turtle, with all attributes accessible)
Basic Movement

Import the turtle library for use

Import turtle

Initialise the turtle on the screen

usr_turtle.reset()

Stop the turtle from further intruption

turtle.done()

usr_turtle.goto(<x_coor >, <y_coor>) usr_turtle.setpos(<x_co or>, <y_coor>)

usr_turtle.forward(<pixels>)
Move the turtle ahead of its present direction

Move the turtle back to the direction if its tail

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>)

Rotate the turtle rightward by <angle> degrees

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()

Set the width of lines drawn by turtle in pixels

Take up the turtle Not drawing when moving

turtle.begin_fill() <Start drawing>


Fill the shape drawn by the turtle with fill colour

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

Set colour for 2 types of colours

usr_turtle.color(<pen_col or>, <fill_color>) usr_turtle.color()


pen colour and fill colour

usr_turtle.dot(<integer_diameter>, <colour>)
Define the dot size and drop a dot Geometry

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

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()
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

Set the background colour of turtle screen

turtle.bgcolor()

Set the background image to the <gif_image_file> 9

turtle.bgpic(<gif_image_file>)

Turtle system settings

Use the self-defined world or standard for turtle

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

turtle.setup(width=<screen_% or pixel>, height=<screen_% or pixel>)

Define the coordinates of the new world Recurring functions Define new turtles

turtle.setworldcoordinates(<left>, <bottom>, <right>, <top>) turtle.ontimer(<function>, <time_in_millisecond>) turtle.addshape (<gif_image_file>)


User defined shape can be used only after addshape

Recur the function per <time_in_millisecond> infinitely

Predefined shapes: Arrow, Turtle, Circle, Square, Triangle, Classic

usr_turtle.shape (<Shape_name>)

<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> = []
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

Turtle Functions Event Handling


usr_turtle.on (Mouse movement) No brackets after <event_function> (i.e. <>(), Run the <event_function> when the turtle in clicked by mouse

usr_turtle.onclick (<event_function>)

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

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.onkeypress (<event_function>, <key>)

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 library Managing python time


Time halt Python uptime Wait for <time_in_second> seconds to next statement Return the uptime of python, in <float_type> second starting from 0

time.sleep(<time_in_second>) time.clock()

Condition: Used for delay in pressing/ leaving on/from a note Smooth time.clock() >>> 6.182458438486231 Program

Random Library Import random


Randomise data Shuffling list Generate integers between int_l and int_h

random.randrange(<int_l>, <int_h+1>) random.shuffle(<list_type>)

Randomise an integer between (Inclusive) integer_l and integer_h Randomise a float number between <low> and <high> (not inclusive)

random.randint(<int_l>, <int_h>)) random.uniform(<low, <high>)

Randomise the orders of all <list_type> items

(External Library) Music Functions import pygame.midi


Initialisation and Closing
Import the midi module for playing music Import the time module for time control Initialise the MIDI (playing music) module Create an output to play music Close Music output Close the MIDI module Quit the MIDI system

import pygame.midi import time pygame.midi.init() output = pygame.midi.Output(pygame.midi.get_default_output_id()) output.close() pygame.midi.quit()

12

Note On/ Off

output.note_on(<pitch>, <volume>, <channel>)


Drum Channel <pitch> <instrument>

output.note_off(<pitch>, <volume>, <channel>) Channel in range(16) Volume in range(128)


127: 0 9

Pitch, Volume, Channel

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>)

L-System (Start value, Replacement rules, )


Explanation Variables that have replacement rules F: Usually represents forward Initial string from further replacement Define the angle for the turtle to be rotated (+, -)

Variables = { F }

Constant that have predefined command +: Turn left, -: Turn right

Constant = {+, - }

Starting string = FX+F Angle = 90

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

You might also like