COMP1021_HKUST@Spring2013
Transcript of COMP1021_HKUST@Spring2013
-
7/23/2019 COMP1021_HKUST@Spring2013
1/14
1
COMP1021: PYTHON SYNTAX BOX
ContentsBasic Syntax .................................................................................................................................................................................................................................................. 2
Modular programming ................................................................................................................................................................................................................................ 4
Advanced Syntax ........................................................................................................................................................................................................................................ 5
PythonOptimisation .................................................................................................................................................................................................................................. 7
PythonFile Handling.................................................................................................................................................................................................................................. 7
Control Statements ...................................................................................................................................................................................................................................... 8
Turtle FunctionsImport turtle .................................................................................................................................................................................................................... 8Turtle FunctionsEvent Handling ............................................................................................................................................................................................................. 11
Time libraryManaging python time ...................................................................................................................................................................................................... 12
Random LibraryImport random ............................................................................................................................................................................................................ 12
(External Library) Music Functionsimport pygame.midi..................................................................................................................................................................... 12
Initialisation and Closing ........................................................................................................................................................................................................................ 12
L-System (Start value, Replacement rules, ) ........................................................................................................................................................................................ 13
Appendix-Instrument ................................................................................................................................................................................................................................. 14
-
7/23/2019 COMP1021_HKUST@Spring2013
2/14
2
Basic SyntaxI/O
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)
= input()Prompt a string Input a string
Conversion
Functions int()Convert into str()Convert any into
ord()Return the ASCII code of the char in decimal number system
chr()Return the char with specified ordinal value
Arithmetic
Functions round(, )
return Round the into float number with If not set: Convert into integerIf = 0, data type remains unchanged
round(, )
return Does nothing with even with greater than 0
max ()Return the max value
max ()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
# Comments on a single line
Operators+= (a = a + )
Shorthand Assignment ( = )
// (Division integer), % (Mod)Truncated:
(e.g.) 8.5 % 2 = 0.5 (Modulus operator: No conversion)
==, !=, >=, , >> 2.0000000000000001 == 2True>>> 2.000000000000001 == 2False>>> type(2/2)>>> type(2//2)
-
7/23/2019 COMP1021_HKUST@Spring2013
3/14
3
Precedence(dec)
() ** - * / % // + - < > != == not and or
Bracket Power Unary operator Multiple operator Arithmetic operator Comparison operator Logical operator
True/ FalseTrue or || > 0 (Non-zero) False or = 0
Break andContinue
Statement
breakCurrent Loop Structure Current Loop
Loop Structure
continueCurrent Iteration
Next Iteration iterationcontinue 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 import sys #Recognise System Error
try:
except :
else:
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 { (Big bracket) or ; (Semi-colon)
Replaced by indentation in Python
Indentation
Indentation takes over any structural brackets Indentation wrong Syntax Error
RangeListStep
start or endValuePositive Step: start = 0 , end = len()
Negative Step: start = ord(last item), end =Pressing Kill the program in a friendly way
-
7/23/2019 COMP1021_HKUST@Spring2013
4/14
4
Modular programmingDefining
functions def (,, ):
Define your own function, parameters ProcedureDefine
return Return a value and end Function
Variables: Function Variables
localized
Global Variable vs. Local variable
Global vs.
Local global can be used outside modules
= Local variable is limited to functions
Class
and
objects
class :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, , )Define Function 1st self
Class Functions __init__ variables
self. = variables self. Call
(@Class)
= (,, )
Define new object as a member of the class
Instance Objects (Attribute Reference) (Class obj.) Method Objects ( ) Property ( )
-
7/23/2019 COMP1021_HKUST@Spring2013
5/14
5
Advanced SyntaxRange
(List)
(Array)
range(, ,)
A temporary list consisting integers from to
Step: +1 +
list(range(0, 3)) == 0, 1, 23 - 1
range(, ,
)Range from large to small, with negative step
[int_h]
[int_l-1]
range(, )Range from to - 1
(e.g. of ): funny[-1:2:-1] == yn
funny[-1:2:] == funny[2:-1:] == nn
[, , ]Self-defined set starting with item 0 (ordinal value == 0)
character == []e.g. p == ape[1]
String is a list of characters
List and tuple= [, ,]
Items can be in different types
Enclosed by a pair of square brackets
Can be modified
= (, ,)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
[0]: Leftmost item
negative ordinal value: from -1 from right
[-1]: Rightmost item
List
(Functions) .insert(,
)
Insert an into the of the
.remove ()Remove the from String
.append()Append an to the
[::]
:
remains unchanged
Output an modified with specified features
.index()Return the position of the in the list
= .pop()Remove the last item in the list and contain with
-
7/23/2019 COMP1021_HKUST@Spring2013
6/14
6
Return: is not in the list Default = len() - 1
Dictionary= List type with
(not onlyautomatically
assigned
integer)
(When calling
them, the order
of all items arerearranged)
= { : ,
: , }[] =
for key, value in .items():
print(key, value)Print out () line by line
.items()dict_items([(, ), (,), ])
.values()dict_values([, , ])
del []Delete the item (key and value) with
del
: Can be used for any :
Remove its memory location
Assessing Items
.keys()dict_keys([, , , ])
Nested List
(record)
(3D structure)
[x_axis][y_axis][z_axis]
Excel Database Record
2D Structure Surface Datum 3D Structure Cube Datum
StringTuple List
Tuple
char
len()Return the length of the list = ord([-1]) + 1
[::]
(e.g.) funny[1:3] == un(Not unn )
Default: == 0, == len(string_type>)
char
+ Text concatenation:
(e.g.) fun + kid == funkid
* copies of :
(e.g.) fun * 3 == funfunfun
-
7/23/2019 COMP1021_HKUST@Spring2013
7/14
7
PythonOptimisationTurtle library
turtle.undo()Undo the previous turtle process
turtle.setundobuffer() can be None : undo buffer
Improt syssys.getrecursionlimit()
Return the size of the stack for python
sys.setrecursionlimit()
Set the size of the stack to Stack
PythonFile HandlingEscape
characters \tTab character
\nNew line character
Read &
Write files = 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 modeWhenever the file is opened this way, everything in the file is cleared.
.write()Write the to the
.close()Free up System resources
: Will be in _io.TextIOWrapper class (not str class)
for line in : statement []
.readlines() Lines items
Remove
char
(String)
Default = space character
.strip
.strip()
.lstrip()
.rstrip())
String
list = .split()
Slice at all positions of Create a
-
7/23/2019 COMP1021_HKUST@Spring2013
8/14
8
Control StatementsIf Statement
if : If condition if true, run the process
elif :
else: If Statemtn If else if else
While Loop while : Condition == True, break or condition == False
For Loopfor in :
_ variable (e.g.) for _ in range(10):Integer or character = List items, List ordinal item
Turtle FunctionsImport turtle
(usr_turtle:User-defined turtle)(turtle: System turtle, with all attributes accessible)Basic
Import turtleImport the turtle library for use
usr_turtle.reset()Initialise the turtle on the screen
turtle.done()Stop the turtle from further intruption
Movementusr_turtle.goto(, )
usr_turtle.setpos(, )Initial position (middle) = 0, 0
Move the turtle to a specific coordinateon the screen
usr_turtle.forward()Move the turtle ahead of its present direction
usr_turtle.backward()Move the turtle back to the direction if its
tail
usr_turtle.left()Rotate the turtle leftward by
degrees
usr_turtle.right()Rotate the turtle rightward by
degrees
usr_turtle.speed()0: Instant ; 1: Slow < 10: Fast
Drawingusr_turtle.width()
usr_turtle.up() usr_turtle.down()Put down the turtle Draw when moving
-
7/23/2019 COMP1021_HKUST@Spring2013
9/14
9
Set the width of lines drawn by turtle in
pixels
Take up the turtle Not drawing when
moving
turtle.begin_fill()
turtle.end_fill()
Fill the shape drawn by the turtle with fillcolour
usr_turtle.fillcolor()Set fill colour in colour
usr_turtle.fillcolor()Return the present fill color
usr_turtle.color()Set colour for both fill colour and pen
colour
usr_turtle.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(,
)Define the dot size and drop a dot
usr_turtle.write(, align=,
font = (, )Write on with the 1st char of on turtle
Geometryusr_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 screenTo be used after usr_turtle.tracer(False)
usr_turtle.clear()Clear the drawings from , not
other turtles
usr_turtle.hideturtle()
usr_turtle.showturtle()Turtle
turtle.tracer ()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()Set the background colour of turtle screen
turtle.bgpic()Set the background image to the
-
7/23/2019 COMP1021_HKUST@Spring2013
10/14
10
Turtle system
settings turtle.mode(world) /
turtle.mode(standard)Use the self-defined world orstandard 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
Recurringfunctions turtle.ontimer(, )
Recur the function per infinitely
Define new
turtles usr_turtle.shape()
Predefined shapes:Arrow, Turtle, Circle,
Square, Triangle, Classic
turtle.addshape()
User defined shape can be used only afteraddshape
=turtle.Turtle()
Define new turtle with name =
usr_turtle.shapesize(, )
Define the turtle size with heights and width
= []
.append(turtle.Turtle())
Make good use of append(), instead of predefining the amount of l ist items (e.g.)turtles[i] = usr_turtle.Turtle()
-
7/23/2019 COMP1021_HKUST@Spring2013
11/14
11
Turtle FunctionsEvent Handlingusr_turtle.on
(Mouse
movement)
No brackets
after
(i.e. (),
usr_turtle.onclick ()Run the when the turtle in clicked by
mouse
turtle.ontimer (,)
Run the according to the timer
usr_turtle.ondrag ()Run the when users drags the turtle
usr_turtle.ondrag (usr_turtle.goto)Move the turtle according to your mouse movementFor 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.ycor()Return the y coordinate of the turtle
usr_turtle.on
(KB, MOUSE,
clicking)
turtle.onscreenclick ()Run the when the screen is clicked by
mouse
turtle.onkeyrelease(,)
Run the Run the when the is released
turtle.onkeypress (,
)Run the when the is pressed
turtle.listen()Keep listening any keyboard event
Run this like usr_turtle.done(), must-have + Program
All turtle.on + Related to : Requires def (null_x, null_y)
-
7/23/2019 COMP1021_HKUST@Spring2013
12/14
12
Time libraryManaging python timeTime halt
time.sleep()Wait for seconds to next statement
Condition: Used for delay in pressing/ leaving on/from a note
Smooth
Python uptimetime.clock()
Return the uptime of python, in second starting from 0
time.clock()>>> 6.182458438486231
Program
Random LibraryImport randomRandomise data
random.randrange(, )Generate integers between int_l and int_h
random.randint(, ))Randomise an integer between (Inclusive) integer_l and integer_h
Shuffling listrandom.shuffle()
Randomise the orders of all items
random.uniform(
-
7/23/2019 COMP1021_HKUST@Spring2013
13/14
13
Note On/
Off output.note_on(, , )Drum Channel
output.note_off(, ,)
Pitch,
Volume,Channel Pitch in range(128)Note in range(24, 108) Channel inrange(16)
Default 0
Drum 9
Volume in range(128)127:
(For
== 0)
output.set_intstrument()Instrument code in range (0, 127)
L-System (Start value, Replacement rules, )Explanation
Variables = { F }Variables that have replacement rules
F: Usually represents forward
Constant = {+, - }Constant that have predefined command+: Turn left, -: Turn right
Starting string = FX+FInitial string from further replacement
Rules = F FF-F-F++Rules to replace the command char in string
Angle = 90Define the angle for the turtle to be rotated (+, -)
Iteration = 4Number of iterations to be run
-
7/23/2019 COMP1021_HKUST@Spring2013
14/14
14
Appendix-Instrument0 Acoustic Grand
Piano
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 Noise98 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
103 FX 8 (sci-fi) 111 Shanai 119 Reverse Cymbal 127 Gunshot