Game Scripting with Python – Tim Glasser

Game Scripting with Python – Tim Glasser

1

Game Scripting with Python – Tim Glasser

Contents
Week 1 Lecture: Intro to Python and IDLE Lab: Start Overview assignments Homework: Finish Overview assignments. Week 2: Lecture: Syntax Lab: Syntax assignments Homework: Complete Syntax assignments Week 3: Lecture: Control Flow Lab: Control Flow assignments Homework: Complete Control Flow assignments Week 4: Lecture: Functions Lab: Functions assignments Homework: Complete Functions assignments Week 5: Lecture: Numbers and Strings in Detail Lab: Numbers and Strings in Detail assignments Homework: Complete Numbers and Strings in Detail assignments Week 6: Lecture: Lists, Dictionaries and Tuples Lab: Lists, Dictionaries and Tuples assignments Homework: Complete Lists, Dictionaries and Tuples assignments Week 7: Lecture: Object Oriented Programming Lab: Start end term project with PyGame Homework: End term project with PyGame

2

Game Scripting with Python – Tim Glasser Week 8: Lecture: Input and Output Lab: Input and Output assignments Homework: Complete Input and Output assignments Week 9: Lecture: Modules Lab: Modules assignments Homework: Complete Modules assignments Week 10: Lecture: Handling Errors Lab: Handling Errors assignments Homework: Complete Handling Errors assignments Week 11: Lecture: Summary of the Course Lab: Show and tell end-term project Homework: Appendix A Tic Tac Toe Appendix B PyGame Appendix C Object Oriented Programming with Pygame

3

Game Scripting with Python – Tim Glasser

Week 1 - Introduction
Why Python? Python is a dynamic object-oriented programming language that runs on Windows, Linux/Unix, Mac OS X, Palm Handhelds, and Nokia mobile phones. Python has also been ported to the Java and .NET virtual machines. It is distributed under an OSIapproved open source license that makes it free for programmers to use, even for commercial products. • • • • Open Source/Free Manages Complexity Object Oriented Powerful Expandability Packages Industry Darling MotionBuilder Maya Major Studios

A Simple Example Let’s write a simple Python program in a script. All python files will have extension .py. So put the following source code in a test.py file. #!/usr/bin/python print "Hello, Python!" This will produce following result: Hello, Python! You have seen a simple Python program in interactive as well as script mode, now lets see few basic concepts related to Python Syntax:

4

Game Scripting with Python – Tim Glasser

Another Example Here is another slightly more complex example. Suppose I wish to find the value of:

g ( x) =

x 1 − x2

for x = 0.0, 0.1, ..., 0.9. I could find these numbers by placing the following code in a file, say fme.py, and then running the program by typing python fme.py at the command-line prompt. for i in range(10): x = 0.1*i print x print x/(1-x*x)

This will produce following output: 0.0 0.0 0.1 0.10101010101 0.2 0.208333333333 0.3 0.32967032967 0.4 0.47619047619 0.5 0.666666666667 0.6 0.9375 0.7 1.37254901961 0.8 2.22222222222 0.9

5

Game Scripting with Python – Tim Glasser 4.73684210526 How does the program work? First, Python’s range() function is an example of the use of lists. Lists are absolutely fundamental to Python. Resist the temptation to treat it as the English word “list,” instead always think about the Python construct list. Python’s range() function returns a list of consecutive integers, in this case the list [0,1,2,3,4,5,6,7,8,9]. As you can guess, this will result in 10 iterations of the loop, with i first being 0, then 1, etc. The code:

for i in [2,3,6]: Would give us three iterations, with i taking on the values 2, 3 and 6. A More Complex Example This code reads a text file, specified on the command line, and prints out the number of lines and words in the file:

# reads in the text file whose name is specified on the # command line, and reports the number of lines and words import sys def checkline(): global l global wordcount w = l.split() wordcount += len(w) wordcount = 0 f = open(sys.argv[1]) flines = f.readlines() linecount = len(flines) for l in flines: checkline() print linecount, wordcount

Say for example the program is in the file tme.py, and we have a text file test.txt with contents:

6

’This is an’. Each line is a string. Since sys is not loaded automatically. For floating-point. let’s explain sys.Game Scripting with Python – Tim Glasser This is an example of a text file.argv[1] will be the string ’x’ (strings in Python are generally specified with single quote marks). one of whose member variables is argv. the first and last of which are blank) If we run this program on this file. The readlines() function of the file class returns a list (keep in mind. the result is: python tme.argv[1]) created an object of file class ( Python is an Object Oriented Language). the value returned by calling readlines() is the five-element list [’’.argv. those command-line arguments are of course strings. say. “list” is an official Python term) consisting of the lines in the file. in which we run our program on the file x. we’d use int(). The latter is a Python list.py x 5 8 There are some features in this program which were not in the first example: • • • • • • use of command-line arguments file-manipulation mechanisms more on lists function definition library importation introduction to scope Introduction to Command-Line Arguments First.’example of a’. sys.’text file’. (There are five lines in all. If those strings are supposed to represent numbers. there is an end-of-line character in each string. Since the file here consisted of five lines. an integer argument. in Python. in Python we’d use float() Introduction to File Manipulation The line: f = open(sys. If we had. in this case tme.’’] (Though not visible here. we could convert them. Python includes a module named sys. and that string is one element of the list. element 0 of the list is the script name.py. we needed the import line.) 7 . In our example here. and assigned it to f . In Python.

So. For example: 2 + ’1.py above.’is’.’an’]. It splits a string into a list of words. a variable x might be bound to an integer at one point in your program and then be rebound to a class instance at another point. in checkline() when l is ’This is an’ then the list w will be equal to [’This’. sequences (lists or tuples) and dictionaries Strings v Numerical Values Python does distinguish between numbers and their string representations. Python would assume that l and wordcount are local to checkline() if we don’t inform it otherwise. the Python interpreter does internally keep track of the type of all objects. Python uses dynamic typing. the variable flines does not exist until the statement: flines = f. []. We do the latter with the global keyword.) Types of Variables/Values As is typical in scripting languages.readlines() is executed.). in this case. In other words. w will be equal to the empty list. In other words. in the program tme. for instance. etc. tested for in an if statement. A variable is created when the first assignment to it is executed. Thus Python variables don’t have types. but their values do. However.Game Scripting with Python – Tim Glasser Declaration. The method ( a method is a function contained in a class) split() is a member of the string class. Python’s types include notions of scalars. Local v Global If a function includes any code which assigns to a variable. Scope and Functions Variables are not declared in Python. Built-In Functions The function len() returns the number of elements in a list. the number of lines in the file (since readlines() returned a list in which each element consisted of one line of the file). which is blank. in the code for checkline(). So. The functions eval()and str() can be used to convert back and forth.5’ 8 . type in the sense of C/C++ int or float is not declared in Python. Also a variable which has not been assigned a value yet has the value None (and this can be assigned to a variable. For example. (In the case of the first line. then that variable is assumed to be local.

we check whether name is main .5’) 3. all of the following (some to be explained below) apply to any sequence type: • • • • • The default is to use blank characters as the splitting criterion. let’s add print __name__ to the code in fme.5’ There are also int() to convert from strings to integers.g. If the answer is yes. the commonalities. So. otherwise it was imported. For example. and the module currently being run is referred to as the variable __name__. to test whether a given module is running on its own.28’) 5. which are all array-like but with some differences. The top-level program is known to the interpreter as ‘__main__‘ . i. or via import. but other characters or strings can be used.py then the code in fme.Game Scripting with Python – Tim Glasser causes an error.e. you are in the top level. x[i]) The built-in len()function to give the number of elements in the sequence Slicing operations. as follows.py: 9 . versus having been imported by other code. but 2 + eval(’1. the extraction of subsequences The use of + and * operators for concatenation and replication The Use of name In some cases. and float(). This can be determined through Python’s built-in variable name .py is the top-level program. you type python fme.5’)) ’3. If.5 and str(2 + eval(’1. and your code was not imported. The use of brackets to denote individual elements (e. Whatever the Python interpreter is running is called the top-level program. it is important to know whether a module is being executed on its own.2800000000000002 Sequences Lists are actually special cases of sequences. for instance. to convert from strings to floating-point values: n = int(’32’) 32 x = float(’5. Note though.

.py: 10 .3 0.1 0.3 0. but printed out fme the second time. So.py __main__ 0.2 0.. [remainder of output not shown] Our module’s statement print __name__ printed out main the first time. when we run it on its own as python fme. [remainder of output not shown] Now look what happens if we run it from within Python’s interactive interpreter: >>> __name__ ’__main__’ >>> import fme Fme 0.Game Scripting with Python – Tim Glasser print __name__ for i in range(10): x = 0. First.208333333333 0.0 0...10101010101 0.1*i print x print x/(1-x*x) Let’s run the program twice.32967032967 .1 0.0 0.208333333333 0.0 0. let’s change our example above to fme2.2 0.32967032967 .10101010101 0.0 0.

Instead. this will be a vital point in using debugging tools.main() must be called. the code won’t be executed right away.10101010101 0.1*i print x print x/(1-x*x) if __name__ == ’__main__’: main() The advantage of this is that when we import this module. Here is an example of the latter: >>> import fme2 >>> fme2. 11 .1 0.47619047619 . stores the names in variables called name1 and name2.2 0.0 0.fme2. Among other things.208333333333 0. So get in the habit of always setting up access to main() in this manner in your programs.1) What is the difference between using "+" and ". says hello to both of them.32967032967 0.4 0." in a print statement? Try it! 1. Exercises: 1.2) Write a program that asks two people for their names.0 0.3 0.Game Scripting with Python – Tim Glasser def main(): for i in range(10): x = 0. either by the importing module or by the interactive Python interpreter...main() 0.

The script adds 3 to that number. then display the user’s random hand.4) Write a script that defines a card ( name value and suit). until the user enters quit 1. Then multiplies the result by 2. 1. subtracts 4. then prints the result. 1.6) Write a python script that prints the following figure \ | / @ @ * \"""/ 12 . subtracts twice the original number.3) Write a script that asks a user for a number.Game Scripting with Python – Tim Glasser 1. adds 3. then print it back again. It should ask the user how many cards they want.5) Create a Python script that uses a while loop to read in a line of text that the user enters.

These reserved words may not be used as constant or variable or any other identifier names. And Assert Break Class Continue Def exec finally for from global if 13 not or pass print raise return . or other object. Keywords contain lowercase letters only. and % within identifiers. Reserved Words: The following list shows the reserved words in Python. class. and digits (0 to 9). the identifier is a language-defined special name. $. If the identifier also ends with two trailing underscores. Python is a case sensitive programming language. Python Identifiers: A Python identifier is a name used to identify a variable. Starting an identifier with two leading underscores indicates a strongly private identifier. module.Game Scripting with Python – Tim Glasser Week 2 – Syntax Overview Invoking the interpreter with a script parameter begins execution of the script and continues until the script is finished. Python does not allow punctuation characters such as @. Starting an identifier with a single leading underscore indicates by convention that the identifier is meant to be private. the interpreter is no longer active. Here are following identifier naming convention for Python: Class names start with an uppercase letter and all other identifiers with a lowercase letter. Thus Manpower and manpower are two different identifiers in Python. underscores. When the script is finished. function. An identifier starts with a letter A to Z or a to z or an underscore (_) followed by zero or more letters.

The number of spaces in the indentation is variable. Blocks of code are denoted by line indentation. which is rigidly enforced. Following is the example having various statement blocks: Note: Don't try to understand logic or different functions used. but all statements within the block must be indented the same amount. in Python all the continuous lines indented with similar number of spaces would form a block. Both blocks in this example are fine: if True: print "True" else: print "False" However. "w") except IOError: import in is lambda try while with yield 14 . Just make sure you understand the various blocks even if they are without braces. the second block in this example will generate an error: if True: print "Answer" print "True" else: print "Answer" print "False" Thus.Game Scripting with Python – Tim Glasser Del Elif Else Except Lines and Indentation: One of the first caveats programmers encounter when learning Python is the fact that there are no braces to indicate blocks of code for class and function definitions or flow control. #!/usr/bin/python import sys try: # open file stream file = open(file_name.

close() file_name = raw_input("Enter filename: ") if len(file_name) == 0: print "Next time please enter something" sys.exit() try: file = open(file_name. 'Friday'] 15 . or () brackets do not need to use the line continuation character.exit() file_text = file. allow the use of the line continuation character (\) to denote that the line should continue. 'Tuesday'. For example: total = item_one + \ item_two + \ item_three Statements contained within the []. file_finish. "r") except IOError: print "There was an error reading file" sys. print "' When finished" while file_text != file_finish: file_text = raw_input("Enter text: ") if file_text == file_finish: # close the file file. {}. Python does.write("\n") file. 'Thursday'. 'Wednesday'.write(file_text) file. file_name sys.close break file.read() file. however. For example: days = ['Monday'.Game Scripting with Python – Tim Glasser print "There was an error writing to".close() print file_text Multi-Line Statements: Statements in Python typically end with a new line.exit() print "Enter '".

# This is a comment.Game Scripting with Python – Tim Glasser Quotation in Python: Python accepts single ('). Python! A comment may be on the same line after a statement or expression: name = "Madisetti" # This is again comment You can comment multiple lines as follows: # This is a comment. double (") and triple (''' or """) quotes to denote string literals. too. as long as the same type of quote starts and ends the string. all the following are legal: word = 'word' sentence = "This is a sentence. All characters after the # and up to the physical line end are part of the comment. The triple quotes can be used to span the string across multiple lines. # second comment This will produce following result: Hello. # I said that already. Python!".""" Comments in Python: A hash sign (#) that is not inside a string literal begins a comment. #!/usr/bin/python # First comment print "Hello. # This is a comment. Using Blank Lines: 16 . and the Python interpreter ignores them. too." paragraph = """This is a paragraph. For example. It is made up of multiple lines and sentences.

while.") Here "\n\n" are being used to create two new lines before displaying the actual line. and Python totally ignores it. sys.write(x + '\n') Multiple Statement Groups as Suites: Groups of individual statements making up a single code block are called suites in Python. such as if. Example: if expression : suite elif expression : suite else : 17 . x = 'foo'.stdout. you must enter an empty physical line to terminate a multi-line statement. This is a nice trick to keep a console window open until the user is done with an application. are those which require a header line and a suite. is known as a blank line.Game Scripting with Python – Tim Glasser A line containing only white-space. ) allows multiple statements on the single line given that neither statement starts a new code block. def. possibly with a comment. Compound or complex statements. Multiple Statements on a Single Line: The semicolon ( . and class. Header lines begin the statement (with the keyword) and terminate with a colon ( : ) and are followed by one or more lines which make up the suite. Waiting for the User: The following line of the program displays the prompt. Press the enter key to exit. Once the user presses the key. the program ends. In an interactive interpreter session. and then waits for the user to press the Enter key: #!/usr/bin/python raw_input("\n\nPress the enter key to exit. Here is a sample snip using the semicolon: import sys.

this will produce following result: 100 1000. While running this program. The equal sign (=) is used to assign values to variables. respectively. The declaration happens automatically when you assign a value to a variable. The variable is stored as an object. For example: #!/usr/bin/python counter = 100 miles = 1000. This means that when you create a variable you reserve some space in memory. or characters in these variables.0 name = "John" print counter print miles print name Here 100. value and data type. by assigning different data types to variables. Therefore. and the operand to the right of the = operator is the value stored in the variable. Based on the data type of a variable. Python code number = 1 name value data type int greeting = "hello" greeting "hello" string number 1 The operand to the left of the = operator is the name of the variable. you can store integers. decimals. the interpreter allocates memory and decides what can be stored in the reserved memory. miles and name variables.Game Scripting with Python – Tim Glasser suite Variables Variables are nothing but reserved memory locations to store values. Assigning Values to Variables: Python variables do not have to be explicitly declared to reserve memory space.0 and "John" are the values assigned to counter. the object has a name.0 John # An integer assignment # A floating point # A string 18 . 1000.

For example: a=b=c=1 Here. and all three variables are assigned to the same memory location. Simple Data Types: The data stored in memory can be of many types. and one string object with the value "john" is assigned to the variable c. which mean that changing the value of a number data type results in a newly allocated object. c = 1.s age is stored as a numeric value and his or her address is stored as alphanumeric characters. Python has five standard data types: Numbers String List Tuple Dictionary Python Numbers: Number data types store numeric values. a person. Python has some standard types that are used to define the operations possible on them and the storage method for each of them. They are immutable data types. 2. "john" Here two integer objects with values 1 and 2 are assigned to variables a and b. For example: a. b.Game Scripting with Python – Tim Glasser Multiple Assignments: You can also assign a single value to several variables simultaneously. You can also assign multiple objects to multiple variables. The syntax of the del statement is: 19 . For example. an integer object is created with the value 1. Number objects are created when you assign a value to them. For example: var1 = 1 var2 = 10 You can also delete the reference to a number object by using the del statement.

var2[. Sequence Data Types Strings: 20 .varN]]]] You can delete a single object or multiple objects by using the del statement.. A complex number consists of an ordered pair of real floatingpoint numbers denoted by a + bj.j 9.0 15.53e-7j Python allows you to use a lowercase L with long.3+e18 -90. where a is the real part and b is the imaginary part of the complex number.. -32.6545+0J 3e+26J 4..54e100 70.14j 45. Python displays long integers with an uppercase L.Game Scripting with Python – Tim Glasser del var1[.var3[..322e-36j . but it is recommended that you use only an uppercase L to avoid confusion with the number 1.9 32.2-E12 float complex 3.20 -21. For example: del var del var_a. var_b Python supports four different numerical types: int (signed integers) long (long integers [can also be represented in octal and hexadecimal]) float (floating point real values) complex (complex numbers) Examples: Here are some examples of numbers: Int 10 100 -786 080 -0490 -0x260 0x69 51924361L -0x19323L 0122L 0xDEFABCECBDAECBFBAEl 535633629843L -052318172735L -4721885298529L long 0.876j -.

A list contains items separated by commas and enclosed within square brackets ([]). The plus ( + ) sign is the list concatenation operator. and the asterisk ( * ) is the repetition operator. To some extent.Game Scripting with Python – Tim Glasser Strings in Python are identified as a contiguous set of characters in between quotation marks. One difference between them is that all the items belonging to a list can be of different data type. The plus ( + ) sign is the string concatenation operator. Subsets of strings can be taken using the slice operator ( [ ] and [ : ] ) with indexes starting at 0 in the beginning of the string and working their way from -1 at the end. Python allows for either pairs of single or double quotes. Example: #!/usr/bin/python str = 'Hello World!' print str # Prints complete string print str[0] # Prints first character of the string print str[2:5] # Prints characters starting from 3rd to 6th print str[2:] # Prints string starting from 3rd character print str * 2 # Prints string two times print str + "TEST" # Prints concatenated string This will produce following result: Hello World! H llo llo World! Hello World!Hello World! Hello World!TEST Python Lists: Lists are the most versatile of Python's compound data types. lists are similar to arrays in C. and the asterisk ( * ) is the repetition operator. 21 . The values stored in a list can be accessed using the slice operator ( [ ] and [ : ] ) with indexes starting at 0 in the beginning of the list and working their way to end-1.

Game Scripting with Python – Tim Glasser Example: #!/usr/bin/python list = [ 'abcd'. 'john'] print list # Prints complete list print list[0] # Prints first element of the list print list[1:3] # Prints elements starting from 2nd to 4th print list[2:] # Prints elements starting from 3rd element print tinylist * 2 # Prints list two times print list + tinylist # Prints concatenated lists This will produce following result: ['abcd'. 70. however. 70. 'john'] ['abcd'. 'john'. tuples are enclosed within parentheses. 'john') print tuple # Prints complete list print tuple[0] # Prints first element of the list print tuple[1:3] # Prints elements starting from 2nd to 4th print tuple[2:] # Prints elements starting from 3rd element print tinytuple * 2 # Prints list two times 22 . 2.23. while tuples are enclosed in parentheses ( ( ) ) and cannot be updated. 'john'. 'john'. 786.2 ] tinylist = [123.23] [2.200000000000003] [123. 'john'.23. 'john'.2 ) tinytuple = (123.23. 2. 70.200000000000003. 2. 'john'] Python Tuples: A tuple is another sequence data type that is similar to the list. The main differences between lists and tuples are: Lists are enclosed in brackets ( [ ] ). and their elements and size can be changed. Tuples can be thought of as read-only lists. 786 . 123. Example: #!/usr/bin/python tuple = ( 'abcd'. 786. A tuple consists of a number of values separated by commas. 786 .200000000000003] abcd [786.23. 70. 2. 123. 2. 'john'.23. Unlike lists. 70.

'john') ('abcd'. 70. 786.200000000000003) (123. but are usually numbers or strings. 123. 70.2 ] tuple[2] = 1000 # Invalid syntax with tuple list[2] = 1000 # Valid syntax with list Python Dictionary: Python 's dictionaries are hash table type. 786.'code':6734. 2. 2.200000000000003) abcd (786. 70. 2. 'dept': 'sales'} print dict['one'] # Prints value for 'one' key 23 . 2. Keys can be almost any Python type. 'john'. 'john'. Example: #!/usr/bin/python dict = {} dict['one'] = "This is one" dict[2] = "This is two" tinydict = {'name': 'john'. 'john'.23.23. 786 .2 ) list = [ 'abcd'. because we attempted to update a tuple. 70.23) (2. 'john'. Values. 70.23. They work like associative arrays and consist of key-value pairs. 2. 123. 'john') Following is invalid with tuple. on the other hand. can be any arbitrary Python object. 'john'. 786 . 'john'.200000000000003.23. Dictionaries are enclosed by curly braces ( { } ) and values can be assigned and accessed using square braces ( [] ).which is not allowed.23. Similar case is possible with lists: #!/usr/bin/python tuple = ( 'abcd'.Game Scripting with Python – Tim Glasser print tuple + tinytuple # Prints concatenated lists This will produce following result: ('abcd'.

24 . Converts s to a tuple. Converts x to a floating-point number.Game Scripting with Python – Tim Glasser print dict[2] # Prints value for 2 key print tinydict # Prints complete dictionary print tinydict.imag]) str(x) repr(x) eval(str) tuple(s) list(s) set(s) dict(d) Description Converts x to an integer. 'name'] ['sales'. It is incorrect to say that the elements are "out of order". Creates a complex number. Evaluates a string and returns an object. 'name': 'john'} ['dept'. Creates a dictionary. base specifies the base if x is a string. Converts x to a long integer. Function int(x [. Data Type Conversion: Sometimes you may need to perform conversions between the built-in types.base] ) float(x) complex(real [. 'code': 6734. base specifies the base if x is a string. d must be a sequence of (key.base]) long(x [. There are several built-in functions to perform conversion from one data type to another. 6734.values() # Prints all the values This will produce following result: This is one This is two {'dept': 'sales'. To convert between types you simply use the type name as a function. 'john'] Dictionaries have no concept of order among elements. 'code'. Converts s to a set. These functions return a new object representing the converted value. Converts object x to a string representation.value) tuples. Converts s to a list. Converts object x to an expression string.keys() # Prints all the keys print tinydict. they are simply unordered.

Subtracts right hand operand from left hand operand Multiplication . Converts an integer to an octal string. Converts a single character to its integer value.Adds values on either side of the operator Subtraction . Python Arithmetic Operators: Assume variable a holds 10 and variable b holds 20 then: Operator + * / % Description Addition . Arithmetic Operators Comparision Operators Logical (or Relational) Operators Assignment Operators Conditional (or ternary) Operators Lets have a look on all operators one by one. Converts an integer to a Unicode character.Divides left hand operand by right hand operand and returns Example a + b will give 30 a .Divides left hand operand by right hand operand Modulus .b will give -10 a * b will give 200 b / a will give 2 b % a will give 0 25 . Converts an integer to a character. Converts an integer to a hexadecimal string.Game Scripting with Python – Tim Glasser frozenset(s) chr(x) unichr(x) ord(x) hex(x) oct(x) Converts s to a frozen set. Python language supports following type of operators. Here 4 and 5 are called operands and + is called operator.Multiplies values on either side of the operator Division . Operators What is an operator? Simple answer can be given using expression 4 + 5 is equal to 9.

0 is equal to 4. This is similar to != operator. <= Checks if the value of left operand is less than or equal to the value of right (a <= b) is true. Checks if the value of left operand is greater than or equal to the value of right operand.Game Scripting with Python – Tim Glasser remainder ** Exponent .The division of operands where the result is the quotient in which the digits after the decimal point are removed. if yes then condition becomes true.Performs exponential (power) calculation on operators Floor Division . Example (a == b) is not true. <> (a <> b) is true.0//2. if yes then condition 26 . > (a > b) is not true. if (a < b) is true.0 Python Comparison Operators: Assume variable a holds 10 and variable b holds 20 then: Operator == Description Checks if the value of two operands are equal or not. Checks if the value of two operands are equal or not. if yes then condition becomes true. Checks if the value of left operand is greater than the value of right operand. if values are not equal then condition becomes true. a**b will give 10 to the power 20 // 9//2 is equal to 4 and 9. >= (a >= b) is not true. yes then condition becomes true. if values are not equal then condition becomes true. < Checks if the value of left operand is less than the value of right operand. Checks if the value of two operands are equal or not. != (a != b) is true. operand. if yes then condition becomes true.

Performs floor division on c //= a is equivalent to c = c // a operators and assign value to the left operand 27 . Performs exponential (power) calculation on operators and assign value to the left operand /= %= c %= a is equivalent to c = c % a **= c **= a is equivalent to c = c ** a //= Floor Dividion and assigns a value.Game Scripting with Python – Tim Glasser becomes true. It adds right operand to the left operand and assign the result to left operand Subtract AND assignment operator. Assigns values from right side operands to left side operand Add AND assignment operator. It multiplies right c *= a is equivalent to c = c * a operand with the left operand and assign the result to left operand Divide AND assignment operator. It takes modulus using two operands and assign the result to left operand Exponent AND assignment operator. It subtracts right operand from the left operand and assign the result to left operand Example c = a + b will assigne value of a + b into c += c += a is equivalent to c = c + a -= c -= a is equivalent to c = c – a *= Multiply AND assignment operator. It divides left operand c /= a is equivalent to c = c / a with the right operand and assign the result to left operand Modulus AND assignment operator. Python Assignment Operators: Assume variable a holds 10 and variable b holds 20 then: Operator = Description Simple assignment operator.

Evaluates to true if it finds a variable in the specified sequence and false otherwise. such as strings. Called Logical OR Operator. here not in results in a 1 if x is a member of sequence y. Called Logical NOT Operator. which test for membership in a sequence. here in results in a 1 if x is a member of sequence y. not in Python Identity Operators: Identity operators compare the memory locations of two objects. Example x in y. Logical NOT operator will make false. then condition becomes true. or not Python Membership Operators: In addition to the operators discussed previously. Python has membership operators. condition becomes true. There are two membership operators explained below: Operator in Description Evaluates to true if it finds a variable in the specified sequence and false otherwise. lists. Use to reverses the logical state of its operand. If a condition is true then not(a && b) is false. or tuples.Game Scripting with Python – Tim Glasser Python Logical Operators: There are following logical operators supported by Python language Assume variable a holds 10 and variable b holds 20 then: Operator and Description Example Called Logical AND operator. If both the operands are true then then (a and b) is true. x not in y. There are two Identity operators explained below: Operator Description Example 28 . If any of the two operands are non zero then (a or b) is true.

Game Scripting with Python – Tim Glasser Evaluates to true if the variables on x is y. is is not Python Operators Precedence The following table lists all operators from highest precedence to lowest. divide. same object and true otherwise. Operator ** ~+* / % // +>> << & ^| <= < > >= <> == != Description Exponentiation (raise to the power) Ccomplement. The program should • Ask the user to input the lengths of the sides of the rectangle • Compute the area – Area = length * width 29 . here is results in 1 if id(x) either side of the operator point to the equals id(y). Evaluates to false if the variables on x is not y. unary plus and minus (method names for the last two are +@ and -@) Multiply. here is not results in 1 if either side of the operator point to the id(x) is not equal to id(y). modulo and floor division Addition and subtraction Right and left bitwise shift Bitwise 'AND' Bitwise exclusive `OR' and regular `OR' Comparison operators Equality operators = %= /= //= -= += |= &= >>= Assignment operators <<= *= **= is is not in not in note or and Identity operators Membership operators Logical operators Exercises: 1. Create a program that will compute the area of a rectangle. same object and false otherwise.

Pretend that your program should act like a cash register. Create the following output (assuming "red" is the chosen color). Pass in 3 arguments ( string . and the amount paid. Use "+" and "*". Write a program to calculate compound interest. and then swaps them. Write a program that asks the user to input values for two floating point numbers. The formula for compound interest is : Amount = Current Value * ( 1 + Rate of Interest) ** n (where n is the number compounding periods) 6.Game Scripting with Python – Tim Glasser • Display the result 2. 3. Write a program that asks users for their favorite color. and then responds with the amount of change. float and integer) to a Python script. Hint: you may need more than two variables for this to work. It should prompt the user for two values – the total cost of items. The script prints the arguments out an also adds the float and integer together and prints out the result 30 . The program should then display the values. red red red red red red red red red red red red red red red red red red red red red red red red 7. 5.

all the statements indented by the same number of character spaces after a programming construct are considered to be part of a single block of code. and nested if.else. Note: In Python. if its value is nonzero then the statement(s) block are executed. elif. This tutorial will discuss the programming conditional constructs available in Python.Got a true expression value" print var1 var2 = 0 if var2: print "2 . and a decision is made based on the result of the comparison.. The if statement contains a logical expression using which data is compared. The result of this decision making determines the sequence in which a program will execute instructions. You can control the flow of a program by using conditional constructs. condition is evaluated first. If condition is true that is. Otherwise.Got a true expression value" print var2 print "Good bye!" 31 . The if statement: The if statement of Python is similar to that of other languages. the next statement following the statement(s) block is executed. if. such as if. Example: #!/usr/bin/python var1 = 100 if var1: print "1 ..Game Scripting with Python – Tim Glasser Week 3 Control Structures Conditional constructs are used to incorporate decision making into programs. Python uses indentation as its method of grouping statements. The syntax of the if statement is: if expression: statement(s) Here if statement.

else statement is: if expression: statement(s) else: statement(s) Example: #!/usr/bin/python var1 = 100 if var1: print "1 .Got a false expression value" print var2 print "Good bye!" This will produce following result: 32 . The else statement is an optional statement and there could be at most only one else statement following if .Got a false expression value" print var1 var2 = 0 if var2: print "2 .Got a true expression value 100 Good bye! The else Statement: An else statement can be combined with an if statement.Game Scripting with Python – Tim Glasser This will produce following result: 1 ..Got a true expression value" print var1 else: print "1 ..Got a true expression value" print var2 else: print "2 . An else statement contains the block of code that executes if the conditional expression in the if statement resolves to 0 or a false value. The syntax of the if.

Got a true expression value" print var elif var == 150: print "2 .Got a false expression value" print var 33 .. Example: #!/usr/bin/python var = 100 if var == 200: print "1 ..Got a false expression value 0 Good bye! The elif Statement The elif statement allows you to check multiple expressions for truth value and execute a block of code as soon as one of the conditions evaluates to true. However. there can be an arbitrary number of elif statements following an if.Got a true expression value 100 2 .Got a true expression value" print var else: print "4 . The syntax of the if.Game Scripting with Python – Tim Glasser 1 . the elif statement is optional.Got a true expression value" print var2 elif var == 100: print "3 .elif statement is: if expression1: statement(s) elif expression2: statement(s) elif expression3: statement(s) else: statement(s) Note: Python does not currently support switch or case statements as in other languages. for which there can be at most one statement. Like the else. unlike else.

.else construct inside another if. The syntax of the nested if.elif.. In a nested if construct.. you can have an if...elif.Game Scripting with Python – Tim Glasser print "Good bye!" This will produce following result: 3 ...elif..Got a true expression value 100 Good bye! The Nested if. you can use the nested if construct..else construct may be: if expression1: statement(s) if expression2: statement(s) elif expression3: statement(s) else statement(s) elif expression4: statement(s) else: statement(s) Example: #!/usr/bin/python var = 100 if var < 200: print "Expression value is less than 200" if var == 150: print "Which is 150" elif var == 100: print "Which is 100" elif var == 50: print "Which is 50" elif var < 50: 34 .else Construct There may be a situation when you want to check for another condition after a condition resolves to true....else construct..elif... In such a situation..

The while Loop: The while loop is just one of the looping constructs available in Python. The expression has to be a logical expression and must return either a true or a false value The syntax of the while look is: while expression: statement(s) 35 . When the condition becomes false. the while loop continues until the expression becomes false. This tutorial will discuss the while loop construct available in Python. it may go on the same line as the header statement: Here is an example of a one-line if clause: if ( expression == 1 ) : print "Value of expression is 1" Loops A loop is a construct that causes a section of a program to be repeated a certain number of times. the loop ends and the program control is passed to the statement following the loop. The repetition continues while the condition set for the loop remains true.Game Scripting with Python – Tim Glasser print "Expression value is less than 50" else: print "Could not find true expression" print "Good bye!" This will produce following result: Expression value is less than 200 Which is 100 Good bye! Single Statement Suites: If the suite of an if clause consists only of a single line.

all the statements indented by the same number of character spaces after a programming construct are considered to be part of a single block of code. If expression is true that is. 36 . Note: In Python. count count = count + 1 print "Good bye!" This will produce following result: The count is: 0 The count is: 1 The count is: 2 The count is: 3 The count is: 4 The count is: 5 The count is: 6 The count is: 7 The count is: 8 Good bye! The block here. the next statement following the statement(s) block is executed. This results in a loop that never ends. consisting of the print and increment statements. Example: #!/usr/bin/python count = 0 while (count < 9): print 'The count is:'.Game Scripting with Python – Tim Glasser Here expression statement is evaluated first. Python uses indentation as its method of grouping statements. Otherwise. then the statement(s) block is executed repeatedly until expression becomes false. An infinite loop might be useful in client/server programming where the server needs to run continuously so that client programs can communicate with it as and when required. With each iteration. The Infinite Loops: You must use caution when using while loops because of the possibility that this condition never resolves to a false value. the current value of the index count is displayed and then increased by 1. is executed repeatedly until count is no longer less than 9. Such a loop is called an infinite loop.

Game Scripting with Python – Tim Glasser Example: Following loop will continue till you enter 1 at command prompt: #!/usr/bin/python var = 1 while var == 1 : # This constructs an infinite loop num = raw_input("Enter a number :") print "You entered: ". num print "Good bye!" This will produce following result: Enter a number :20 You entered: 20 Enter a number :29 You entered: 29 Enter a number :3 You entered: 3 Enter a number between :Traceback (most recent call last): File "test. Here is an example of a one-line while clause: while expression : statement The for Loop: The for loop in Python has the ability to iterate over the items of any sequence. such as a list or a string. in <module> num = raw_input("Enter a number :") KeyboardInterrupt Above example will go in an infinite loop and you would need to use CNTL+C to come out of the program. Single Statement Suites: Similar to the if statement syntax. The syntax of the loop look is: 37 . line 5. if your while clause consists only of a single statement.py". it may be placed on the same line as the while header.

Then. fruit print "Good bye!" This will produce following result: Current Letter : P Current Letter : y Current Letter : t Current Letter : h Current Letter : o Current Letter : n Current fruit : banana Current fruit : apple Current fruit : mango Good bye! Iterating by Sequence Index: An alternative way of iterating through each item is by index offset into the sequence itself: Example: 38 .Game Scripting with Python – Tim Glasser for iterating_var in sequence: statements(s) If a sequence contains an expression list. letter fruits = ['banana'. Note: In Python. 'apple'. the statements block is executed. Each item in the list is assigned to iterating_var. Next. all the statements indented by the same number of character spaces after a programming construct are considered to be part of a single block of code. 'mango'] for fruit in fruits: # Second Example print 'Current fruit :'. Python uses indentation as its method of grouping statements. Example: #!/usr/bin/python for letter in 'Python': # First Example print 'Current Letter :'. it is evaluated first. the first item in the sequence is assigned to the iterating variable iterating_var. and the statements(s) block is executed until the entire sequence is exhausted.

letter 39 . Example: #!/usr/bin/python for letter in 'Python': # First Example if letter == 'h': break print 'Current Letter :'. The break statement can be used in both while and for loops. 'apple'. You might face a situation in which you need to exit a loop completely when an external condition is triggered or there may also be a situation when you want to skip a part of the loop and start next execution. fruits[index] print "Good bye!" This will produce following result: Current fruit : banana Current fruit : apple Current fruit : mango Good bye! Here we took the assistance of the len() built-in function. This tutorial will discuss the break. continue and pass statements available in Python. The most common use for break is when some external condition is triggered requiring a hasty exit from a loop.Game Scripting with Python – Tim Glasser #!/usr/bin/python fruits = ['banana'. just like the traditional break found in C. 'mango'] for index in range(len(fruits)): print 'Current fruit :'. which provides the total number of elements in the tuple as well as the range() built-in function to give us the actual sequence to iterate over. The break Statement: The break statement in Python terminates the current loop and resumes execution at the next statement. Python provides break and continue statements to handle such situations and to have good control on your loop.

letter var = 10 # Second Example while var > 0: print 'Current variable value :'. Example: #!/usr/bin/python for letter in 'Python': # First Example if letter == 'h': continue print 'Current Letter :'.Game Scripting with Python – Tim Glasser var = 10 # Second Example while var > 0: print 'Current variable value :'. var var = var -1 if var == 5: continue 40 . The continue statement can be used in both while and for loops. The continue statement rejects all the remaining statements in the current iteration of the loop and moves the control back to the top of the loop. var var = var -1 if var == 5: break print "Good bye!" This will produce following result: Current Letter : P Current Letter : y Current Letter : t Current variable value : 10 Current variable value : 9 Current variable value : 8 Current variable value : 7 Current variable value : 6 Good bye! The continue Statement: The continue statement in Python returns the control to the beginning of the while loop.

the #first FOR else: # else part of the loop 41 . the else statement is executed when the condition becomes false. If the else statement is used with a while loop.num): #to iterate on the factors of the number if num%i == 0: #to determine the first factor j=num/i #to calculate the second factor print '%d equals %d * %d' % (num.i.Game Scripting with Python – Tim Glasser print "Good bye!" This will produce following result: Current Letter : P Current Letter : y Current Letter : t Current Letter : o Current Letter : n Current variable value : 10 Current variable value : 9 Current variable value : 8 Current variable value : 7 Current variable value : 6 Current variable value : 5 Current variable value : 4 Current variable value : 3 Current variable value : 2 Current variable value : 1 Good bye! The else Statement Used with Loops Python supports to have an else statement associated with a loop statements.20): #to iterate between 10 to 20 for i in range(2. If the else statement is used with a for loop. Example: The following example illustrates the combination of an else statement with a for statement that searches for prime numbers from 10 through 20. #!/usr/bin/python for num in range(10.j) break #to move to the next number. the else statement is executed when the loop has exhausted iterating the list.

in stubs for example): Example: #!/usr/bin/python for letter in 'Python': if letter == 'h': pass print 'This is pass block' print 'Current Letter :'.Game Scripting with Python – Tim Glasser print num. letter print "Good bye!" This will produce following result: Current Letter : P Current Letter : y Current Letter : t This is pass block 42 . The pass statement is a null operation. 'is a prime number' This will produce following result: 10 equals 2 * 5 11 is a prime number 12 equals 2 * 6 13 is a prime number 14 equals 2 * 7 15 equals 3 * 5 16 equals 2 * 8 17 is a prime number 18 equals 2 * 9 19 is a prime number Similar way you can use else statement with while loop. nothing happens when it executes. but has not been written yet (e.g. The pass Statement: The pass statement in Python is used when a statement is required syntactically but you do not want any command or code to execute. The pass is also useful in places where your code will eventually go..

Output a message telling them if they were correct or not. Ask the user what the password is once. 2. Use Python strings. You can then remove the statements inside the block but let the block remain with a pass statement so that it doesn't interfere with other parts of the code. Choose a word and store it into a string. Write a program that will find the square root of a number that the user enters. 9. Keep asking them to guess the word until they get the correct answer ( use a while loop). 3. until the user enters a ‘q’ or ‘Q’. Write a program that will loop. It should first ask for two numbers (double). Exercises: 1. Ask the user to input a single character. Rewrite #2 so that it loops continuously until the user enters the correct password. Imagine that you are writing the beginning of a hangman program. subtraction. multiplication and division). then prompt the user for a calculation (char) and use a switch statement to complete the operations. Write a program that acts like a four-function calculator (addition. Create a program that uses a “for” loop to print out the numbers 1-50. The pass statement is helpful when you have created a code block but it is no longer required. 8. 7. 5. and display a message that they either logged in correctly or incorrectly.Game Scripting with Python – Tim Glasser Current Letter : h Current Letter : o Current Letter : n Good bye! The preceding code does not execute any statement or code if the value of letter is 'h'. 4. asking the user to input a single character. and then test to see if the character is a part of the string. Define the word at the top of the program. Write a program to have a user guess an entire word. 43 . Pretend that you program is a login for some service. Choose a word to be the password.

Syntax: def functionname( parameters ): "function_docstring" function_suite return [expression] By default. You can also define parameters inside these parentheses. The code block within every function starts with a colon (:) and is indented. A return statement with no arguments is the same as return None. and you need to inform them in the same order that they were defined. parameters have a positional behavior. Functions provides better modularity for your application and a high degree of code reusing. Defining a Function You can define functions to provide the required functionality. optionally passing back an expression to the caller. def printme( str ): "This prints a passed string into this function" print str return 44 . Example: Here is the simplest form of a Python function. reusable code that is used to perform a single. Python gives you many built-in functions like print() etc. The first statement of a function can be an optional statement . The statement return [expression] exits a function.the documentation string of the function or docstring. Any input parameters or arguments should be placed within these parentheses. but you can also create your own functions. As you already know. This function takes a string as input parameter and prints it on standard screen.Game Scripting with Python – Tim Glasser Week 4 Functions A function is a block of organized. related action. These functions are called user-defined functions. Here are simple rules to define a function in Python: • • • • • Function blocks begin with the keyword def followed by the function name and parentheses ( ( ) ).

3. printme("Again second call to the same function"). you can execute it by calling it from another function or directly from the Python prompt. It means if you change what a parameter refers to within a function. specifies the parameters that are to be included in the function.Game Scripting with Python – Tim Glasser Calling a Function Defining a function only gives it a name. # Now you can call printme function printme("I'm first call to user defined function!"). 45 .2. This would produce following result: I'm first call to user defined function! Again second call to the same function Pass by reference vs value Python passes function parameters using call-by-value. print "Values inside the function: ".4]). For example: #!/usr/bin/python # Function definition is here def changeme( mylist ): "This changes a passed list into this function" mylist. return. Following is the example to call printme() function: #!/usr/bin/python # Function definition is here def printme( str ): "This prints a passed string into this function" print str. the change does not affect the function's caller.append([1. mylist return # Now you can call changeme function mylist = [10.20. and structures the blocks of code. All parameters in the Python language are passed by reference. Once the basic structure of a function is finalized.30].

[1. 4]] Values outside the function: [10. that reference is being over-written. 2. [1. 3. mylist return # Now you can call changeme function mylist = [10. changeme( mylist ). 4] Values outside the function: [10. So this would produce following result: Values inside the function: [10.Game Scripting with Python – Tim Glasser changeme( mylist ). # This would assig new reference in mylist print "Values inside the function: ". mylist The parameter mylist is local to the function changeme. 20. print "Values outside the function: ".3. 20. 30] Function Arguments: You can call a function by using the following types of formal arguments:: • • • • Required arguments Keyword arguments Default arguments Variable-length arguments 46 .30]. 30. 3. 3. 20. 2. Changing mylist within the function does not affect mylist. 2. 30.20. 4]] There is one more example where argument is being passed by reference but inside the function. mylist Here we are maintaining reference of the passed object and appending values in the same object.2. print "Values outside the function: ". The function accomplishes nothing and finally this would produce following result: Values inside the function: [1. #!/usr/bin/python # Function definition is here def changeme( mylist ): "This changes a passed list into this function" mylist = [1.4].

47 . return. To call the function printme() you definitely need to pass one argument otherwise it would give a syntax error as follows: #!/usr/bin/python # Function definition is here def printme( str ): "This prints a passed string into this function" print str. in <module> printme(). line 11. TypeError: printme() takes exactly 1 argument (0 given) Keyword arguments: Keyword arguments are related to the function calls. return. # Now you can call printme function Printme(). the caller identifies the arguments by the parameter name. This allows you to skip arguments or place them out of order because the Python interpreter is able to use the keywords provided to match the values with parameters. You can also make keyword calls to the printme() function in the following ways: #!/usr/bin/python # Function definition is here def printme( str ): "This prints a passed string into this function" print str.py".Game Scripting with Python – Tim Glasser Required arguments: Required arguments are the arguments passed to a function in correct positional order. This would produce following result: Traceback (most recent call last): File "test. Here the number of arguments in the function call should match exactly with the function definition. When you use keyword arguments in a function call.

48 . Following example gives idea on default arguments. it would print default age if it is not passed: #!/usr/bin/python # Function definition is here def printinfo( name. name. print "Age ". age. here order of the parameter does not matter: #!/usr/bin/python # Function definition is here def printinfo( name.Game Scripting with Python – Tim Glasser # Now you can call printme function Printme( str = "My string"). age. Note. return. return. age = 35 ): "This prints a passed info into this function" print "Name: ". This would produce following result: My string Following example gives more clear picture. print "Age ". age ): "This prints a passed info into this function" print "Name: ". This would produce following result: Name: miki Age 50 Default arguments: A default argument is an argument that assumes a default value if a value is not provided in the function call for that argument. name. name="miki" ). # Now you can call printinfo function printinfo( age=50.

printinfo( name="miki" ). This would produce following result: 49 . The general syntax for a function with non-keyword variable arguments is this: def functionname([formal_args.] *var_args_tuple ): "function_docstring" function_suite return [expression] An asterisk (*) is placed before the variable name that will hold the values of all nonkeyword variable arguments. This tuple remains empty if no additional arguments are specified during the function call. 50 ). # Now you can call printinfo function printinfo( 10 ). This would produce following result: Name: miki Age 50 Name: miki Age 35 Variable-length arguments: You may need to process a function for more arguments than you specified while defining the function. These arguments are called variable-length arguments and are not named in the function definition. For example: #!/usr/bin/python # Function definition is here def printinfo( arg1.Game Scripting with Python – Tim Glasser # Now you can call printinfo function printinfo( age=50. unlike required and default arguments. 60. printinfo( 70. *vartuple ): "This prints a variable passed arguments" print "Output is: " print arg1 for var in vartuple: print var return. name="miki" ).

An anonymous function cannot be a direct call to print because lambda requires an expression.. they are not equivalent to inline statements in C or C++. 20 ) This would produce following result: 50 .. Syntax: The syntax of lambda functions contains only a single statement. sum( 20. • • • • Lambda forms can take any number of arguments but return just one value in the form of an expression.. Although it appears that lambda's are a one-line version of a function.. arg2: arg1 + arg2. Lambda functions have their own local namespace and cannot access variables other than those in their parameter list and those in the global namespace. 20 ) print "Value of total : ". They cannot contain commands or multiple expressions. sum( 10. whose purpose is by passing function stack allocation during invocation for performance reasons.Game Scripting with Python – Tim Glasser Output is: 10 Output is: 70 60 50 The Anonymous Functions: You can use the lambda keyword to create small anonymous functions..arg2.argn]]:expression Example: Following is the example to show how lambda form of function works: #!/usr/bin/python # Function definition is here sum = lambda arg1. These functions are called anonymous because they are not declared in the standard manner by using the def keyword. which is as follows: Lambda [arg1 [. # Now you can call sum as a function print "Value of total : ".

Game Scripting with Python – Tim Glasser Value of total : 30 Value of total : 40 The return Statement: The statement return [expression] exits a function, optionally passing back an expression to the caller. A return statement with no arguments is the same as return None All the above examples are not returning any value, but if you like you can return a value from a function as follows: #!/usr/bin/python # Function definition is here def sum( arg1, arg2 ): # Add both the parameters and return them." total = arg1 + arg2 print "Inside the function : ", total return total; # Now you can call sum function total = sum( 10, 20 ); print "Outside the function : ", total This would produce following result: Inside the function : 30 Outside the function : 30 Scope of Variables: All variables in a program may not be accessible at all locations in that program. This depends on where you have declared a variable. The scope of a variable determines the portion of the program where you can access a particular identifier. There are two basic scopes of variables in Python:
• •

Global variables Local variables

51

Game Scripting with Python – Tim Glasser

Global vs. Local Variables: Variables that are defined inside a function body have a local scope, and those defined outside have a global scope. This means that local variables can be accessed only inside the function in which they are declared whereas global variables can be accessed throughout the program body by all functions. When you call a function, the variables declared inside it are brought into scope. Example: #!/usr/bin/python total = 0; # This is global variable. # Function definition is here def sum( arg1, arg2 ): # Add both the parameters and return them." total = arg1 + arg2; # Here total is local variable. print "Inside the function local total : ", total return total; # Now you can call sum function sum( 10, 20 ); print "Outside the function global total : ", total This would produce following result: Inside the function local total : 30 Outside the function global total : 0

Exercises: 1. Write a program that uses a function to calculate the volume of a sphere, volume = 4/3r^3 . It should prompt the user for a radius, then display the result. 2. Rewrite #1 so that it will ask the user if they want to compute another volume, and quit if the answer is n or N. 3. Create functions to compute the area of a triangle, circle and rectangle correctly. 4. Use a debugger to see what happens when you run the program in #3.

52

Game Scripting with Python – Tim Glasser 5. Write a program that uses an array to store 5 grades and add them. Create an error th in the array access so that it tries to access the 6 element of the array. Use a debugger to find the error. 6. Write two functions with the same name (overloaded function) that would both return an integer. If the function receives an integer, it should return the integer value. If it receives a string, it should return the length of the string. Here are the function prototypes long find_length(message) long find_length(number) 7. Imagine that you need a function that will check all of the elements of an array, and make them 0 if they are negative numbers. Test the function using an appropriate main function and array. 8. Use a debugger to see what happens when you run the program in #7.

9. Write a function that displays the times table of whatever number parameter it takes. Use this function to write the times tables up to 12

53

var2[. with E or e indicating the power of 10 (2.var3[.. float (floating point real values) : or floats. var_b Python supports four different numerical types: int (signed integers): often called just integers or ints.5 x 102 = 250).. long (long integers ): or longs.322e-36j 54 .9 float complex 3.14j 45. which means that changing the value of a number data type results in a newly allocated object. They are an immutable data type. The syntax of the del statement is: del var1[. Here are some examples of numbers: int 10 100 -786 51924361L -0x19323L 0122L long 0.varN]]]] You can delete a single object or multiple objects by using the del statement.Game Scripting with Python – Tim Glasser Week 5: Numbers and Strings in Detail (midterm) Number data types store numeric values. For example: var1 = 1 var2 = 10 You can also delete the reference to a number object by using the del statement.5e2 = 2.. written like integers and followed by an uppercase or lowercase L.j 9. Number objects are created when you assign a value to them. For example: del var del var_a. complex (complex numbers) : Don’t worry about these types. represent real numbers and are written with a decimal point dividing the integer and fractional parts.0 15.20 -21. Floats may also be in scientific notation.. are positive or negative whole numbers with no decimal point. are integers of unlimited size.

-32. x and y are numeric expressions Built-in Number Functions: Mathematical Functions: Python includes following functions that perform mathematical calculations.3+e18 -90.53e-7j Python allows you to use a lowercase L with long. The floor of x: the largest integer not greater than x 55 . The ceiling of x: the smallest integer not less than x -1 if x < y. Type complex(x) to convert x to a complex number with real part x and imaginary part zero. or 1 if x > y The exponential of x: ex The absolute value of x. y) to convert x and y to a complex number with real part x and imaginary part y. Type float(x) to convert x to a floating-point number. Type long(x) to convert x to a long integer. 0 if x == y. Type complex(x. y) exp(x) fabs(x) floor(x) Returns ( description ) The absolute value of x: the (positive) distance between x and zero. Function abs(x) ceil(x) cmp(x. Type int(x)to convert x to a plain integer.Game Scripting with Python – Tim Glasser 080 -0490 -0x260 0x69 0xDEFABCECBDAECBFBAEl 535633629843L -052318172735L -4721885298529L 32. you'll need to coerce a number explicitly from one type to another to satisfy the requirements of an operator or function parameter.876j -. But sometimes. Number Type Conversion: Python converts numbers internally in an expression containing mixed types to a common type for evaluation. where a is the real part and b is the imaginary part of the complex number.6545+0J 3e+26J 4. A complex number consists of an ordered pair of real floatingpoint numbers denoted by a + bj.2-E12 . but it is recommended that you use only an uppercase L to avoid confusion with the number 1. Python displays long integers with an uppercase L.54e100 70.

x2. 56 .0 and round(-0.. tuple.5) is 1. A random float r. x2. Both parts have the same sign as x. The square root of x for x > 0 Random Number Functions: Random numbers are used for games. Function choice(seq) randrange ([start.. Python includes following functions that are commonly used.. The largest of its arguments: the value closest to positive infinity The smallest of its arguments: the value closest to negative infinity The fractional and integer parts of x in a two-item tuple.0..Game Scripting with Python – Tim Glasser log(x) log10(x) max(x1. security. stop. The value of x**y. Returns None. simulations. Returns None.) min(x1. and privacy applications. Python rounds away from zero as a tie-breaker: round(0.] stop [. for x> 0 The base-10 logarithm of x for x> 0 .) modf(x) pow(x.5) is 1.step]) random() Returns ( description ) A random item from a list..n]) sqrt(x) The natural logarithm of x. such that x is less than or equal to r and r is less than y seed([x]) shuffle(lst) uniform(x. Randomizes the items of a list in place. Call this function before calling any other random module function. step) A random float r. testing. or string.. such that 0 is less than or equal to r and r is less than 1 Sets the integer starting value used in generating random numbers. A randomly selected element from range(start. y) Trigonometric Functions: Python includes following functions that perform trigonometric calculations. y) round(x [. x rounded to n digits from the decimal point. The integer part is returned as a float.

Converts angle x from radians to degrees. Return the arc tangent of x. thus also considered a substring. Creating strings is as simple as assigning a value to a variable.Game Scripting with Python – Tim Glasser Function acos(x) asin(x) atan(x) atan2(y. in radians. Return the sine of x radians. these are treated as strings of length one. in radians. For example: var1 = 'Hello World!' var2 = "Python Programming" Accessing Values in Strings: Python does not support a character type. sqrt(x*x + y*y). y) sin(x) tan(x) degrees(x) radians(x) Description Return the arc cosine of x. Python treats single quotes the same as double quotes. Return the Euclidean norm. We can create them simply by enclosing characters in quotes. Return the arc sine of x. in radians. Return atan(y / x). The mathematical constant e. in radians. x) cos(x) hypot(x. Return the cosine of x radians. 57 . Mathematical Constants: The module also defines two mathematical constants: Constant pi e Description The mathematical constant pi. Return the tangent of x radians. Strings Strings are amongst the most popular types in Python. Converts angle x from degrees to radians.

". an escape character is preserved. an escape character is interpreted.Hello Python Escape Characters: Following table is a list of escape or non-printable characters that can be represented with backslash notation. Backslash Hexadecimal Description 58 . NOTE: In a double quoted string. in a single quoted string. var1[0] print "var2[1:5]: ". var2[1:5] This will produce following result: var1[0]: H var2[1:5]: ytho Updating Strings: You can "update" an existing string by (re)assigning a variable to another string. var1[:6] + 'Python' This will produce following result: Updated String :.Game Scripting with Python – Tim Glasser To access substrings. The new value can be related to its previous value or to a completely different string altogether. use the square brackets for slicing along with the index or indices to obtain your substring: Example: #!/usr/bin/python var1 = 'Hello World!' var2 = "Python Programming" print "var1[0]: ". Example: #!/usr/bin/python var1 = 'Hello World!' print "Updated String :.

7 Carriage return Space Tab Vertical tab Character x Hexadecimal notation.Returns true if a a*2 will give –HelloHello * [] [:] in a[1] will give e a[1:4] will give ell H in a will give 1 59 . concatenating multiple copies of the same string Slice .Adds values on either a + b will give HelloPython side of the operator Repetition .9. where n is in the range 0.F Concatenation .Gives the character from the given index Range Slice .Game Scripting with Python – Tim Glasser notation \a \b \cx \C-x \e \f \M-\C-x \n \nnn \r \s \t \v \x \xnn String Special Operators: Assume string variable a holds 'Hello' and variable b holds 'Python' then: Operator + Description Example 0x0d 0x20 0x09 0x0b 0x0a 0x1b 0x0c character 0x07 0x08 Bell or alert Backspace Control-x Control-x Escape Formfeed Meta-Control-x Newline Octal notation. a. where n is in the range 0.Creates new strings.f. or A.Gives the characters from the given range Membership .

" print r'\n' prints \n and print R'\n' which precedes the quotation marks. the letter "r. 21) This will produce following result: My name is Zara and weight is 21 kg! Here is the list of complete set of symbols which can be used along with %: Format Symbol %c %s %i %d Character string conversion via str() prior to formatting signed decimal integer signed decimal integer Conversion 60 . Format . Example: #!/usr/bin/python print "My name is %s and weight is %d kg!" % ('Zara'.Performs String formatting See at next section % String Formatting Operator: One of Python's coolest features is the string format operator %. The syntax for raw strings is exactly the same as for normal strings with the exception of the raw string operator.Game Scripting with Python – Tim Glasser character exists in the given string not in Membership .Suppress actual meaning of Escape characters.Returns true if a character does not exist in the given string M not in a will give 1 r/R Raw String . This operator is unique to strings and makes up for the pack of having functions from C's printf() family. prints \n The "r" can be lowercase (r) or uppercase (R) and must be placed immediately preceding the first quote mark.

and any other special characters. including verbatim NEWLINEs. #!/usr/bin/python Functionality Argument specifies width or precision left justification display the sign leave a blank space before a positive number add the octal leading zero ( '0' ) or hexadecimal leading '0x' or '0X'. Triple Quotes: Python's triple quotes comes to the rescue by allowing strings to span multiple lines. pad from left with zeros (instead of spaces) '%%' leaves you with a single literal '%' mapping variable (dictionary arguments) m is the minimum total width and n is the number of digits to display after the decimal point (if appl. depending on whether 'x' or 'X' were used.) 61 . TABs.Game Scripting with Python – Tim Glasser %u %o %x %X %e %E %f %g %G unsigned decimal integer octal integer hexadecimal integer (lowercase letters) hexadecimal integer (UPPERcase letters) exponential notation (with lowercase 'e') exponential notation (with UPPERcase 'E') floating point real number the shorter of %f and %e the shorter of %f and %E Other supported symbols and functionality are listed in the following table: Symbol * + <sp> # 0 % (var) m. The syntax for triple quotes consists of three consecutive single or double quotes.n.

Game Scripting with Python – Tim Glasser para_str = """this is a long string that is made up of several lines and non-printable characters such as TAB ( \t ) and they will show up that way when displayed. or just a NEWLINE within the variable assignment will also show up. """ print para_str. Also note that NEWLINEs occur either with an explicit carriage return at the end of a line or its escape code (\n): this is a long string that is made up of several lines and non-printable characters such as TAB ( ) and they will show up that way when displayed. NEWLINEs within the string." and closing triple quotes. Note how every single special character has been converted to its printed form. Every character you put into a raw string stays the way you wrote it: #!/usr/bin/python print 'C:\\nowhere' This would print following result: C:\nowhere Mow let's make use of raw string. whether explicitly given like this within the brackets [ ]. We would put expression in r'expression' as follows: #!/usr/bin/python print r'C:\\nowhere' This would print following result: 62 . right down to the last NEWLINE at the end of the string between the "up. NEWLINEs within the string. This will produce following result. whether explicitly given like this within the brackets [ \n ]. or just a NEWLINE within the variable assignment will also show up. Raw String: Raw strings don't treat the backslash as a special character at all.

end=len(string)) Determines if string or a substring of string (if starting index beg and ending index 2 3 3 4 5 63 . beg= 0. on error. default is to raise a ValueError unless errors is given with 'ignore' or 'replace'. fillchar) Returns a space-padded string with the original string centered to a total of width columns count(str.Game Scripting with Python – Tim Glasser C:\\nowhere Unicode String: Normal strings in Python are stored internally as 8-bit ASCII. encoding defaults to the default string encoding. or in a substring of string if starting index beg and ending index end are given decode(encoding='UTF-8'. while Unicode strings are stored as 16-bit Unicode. encode(encoding='UTF-8'.errors='strict') Decodes the string using the codec registered for encoding. world!' This would print following result: Hello. Built-in String Methods: Python includes following string methods: SN 1 Methods with Description capitalize() Capitalizes first letter of string center(width.end=len(string)) Counts how many times str occurs in string. endswith(suffix. Unicode strings use the prefix u.errors='strict') Returns encoded string version of string. I'll restrict my treatment of Unicode strings to the following: #!/usr/bin/python print u'Hello. including special characters from most languages in the world. This allows for a more varied set of characters. world! As you can see. just as raw strings use the prefix r. beg=0.

defaults to 8 spaces per tab if tabsize not provided find(str. returns index if found and -1 otherwise index(str. end=len(string)) Same as find(). and false otherwise 6 expandtabs(tabsize=8) Expands tabs in string to multiple spaces. or in a substring of string if starting index beg and ending index end are given. with separator string 18 len(string) Returns the length of the string ljust(width[. beg=0. fillchar]) 19 Returns a space-padded string with the original string left-justified to a total of width columns 64 . but raises an exception if str not found isa1num() Returns true if string has at least 1 character and all characters are alphanumeric and false otherwise 7 8 9 isalpha() 10 Returns true if string has at least 1 character and all characters are alphabetic and false otherwise 11 isdigit() Returns true if string contains only digits and false otherwise islower() 12 Returns true if string has at least 1 cased character and all cased characters are in lowercase and false otherwise 13 14 15 isnumeric() Returns true if string contains only numeric characters and false otherwise isspace() Returns true if string contains only whitespace characters and false otherwise istitle() Returns true if string is properly "titlecased" and false otherwise isupper() 16 Returns true if string has at least one cased character and all cased characters are in uppercase and false otherwise join(seq) 17 Merges (concatenates) the string representations of elements in sequence seq into a string. beg=0 end=len(string)) Determine if str occurs in string.Game Scripting with Python – Tim Glasser end are given) ends with suffix. Returns true if so.

new [. 29 rstrip() Removes all trailing whitespace of string split(str="". but search backwards in string rindex( str. beg=0.count(str)) 30 Splits string according to delimiter str (space if not provided) and returns list of substrings. max(str) Returns the max alphabetical character from the string str min(str) Returns the min alphabetical character from the string str 20 21 22 23 24 replace(old. num=string. end=len(string)) Same as index().Game Scripting with Python – Tim Glasser lower() Converts all uppercase letters in string to lowercase lstrip() Removes all leading whitespace in string maketrans() Returns a translation table to be used in translate function.[. max]) 25 Replaces all occurrences of old in string with new. or at most max occurrences if max given 26 27 rfind(str. Returns true if so. beg=0. all words begin with uppercase.end=len(string)) Same as find(). and the 65 . fillchar]) 28 Returns a space-padded string with the original string right-justified to a total of width columns. but search backwards in string rjust(width.count('\n')) 31 Splits string at all (or num) NEWLINEs and returns a list of each line with NEWLINEs removed startswith(str. and false otherwise 33 34 35 strip([chars]) Performs both lstrip() and rstrip() on string swapcase() Inverts case for all letters in string title() Returns "titlecased" version of string.end=len(string)) 32 Determines if string or a substring of string (if starting index beg and ending index end are given) starts with substring str. split into at most num substrings if given splitlines( num=string. beg=0. that is.

(Hint: if a variable is empty. last name and phone number.) 3) Change the script so that the script prints "Thank you" if either the first name or the last name or the phone number is supplied. its value will be "false". then remove the last five letters from the name and print it out 66 . zfill() retains any sign given (less one zero) Exercises 1) Ask the user to enter a string and print it back in Upper Case. intended for numbers. removing those in the del string 37 upper() Converts lowercase letters in string to uppercase zfill (width) 38 Returns original string leftpadded with zeros to a total of width characters. i 2) Write a script that asks someone to input their first name. 4) Change the script so that only first name and last name are required. If the user does not type at least some characters for each of these. print "Do not leave any fields empty" otherwise print "Thank you". 5) Ask the user to enter their name. deletechars="") 36 Translates string according to translation table str(256 chars). Print "Do not leave all fields empty" otherwise. The phone number is optional.Game Scripting with Python – Tim Glasser rest are lowercase translate(table.

3. 2000]. "b". use the square brackets for slicing along with the index or indices to obtain value available at that index: Example: #!/usr/bin/python list1 = ['physics'. The first index is zero. list2[1:5] 67 . 2000]. 4. Good thing about a list that items in a list need not all have the same type: Creating a list is as simple as putting different comma-separated values between square brackets. There are certain things you can do with all sequence types. Accessing Values in Lists: To access values in lists. 6. 3. dictionaries. 2. Python has built-in functions for finding the length of a sequence. list indices start at 0. slicing. These operations include indexing. the second index is one.its position. 1997. and checking for membership. adding. list2 = [1. Python has six built-in types of sequences (strings. In addition. "c".Game Scripting with Python – Tim Glasser Week 6 More Sequence Types – Lists. 2. "d"]. tuples. multiplying. lists. and so forth. and for finding its largest and smallest elements. 'chemistry'. Python Lists: The list is a most versatile data type available in Python. list1[0] print "list2[1:5]: ". 4. or index. 7 ]. list2 = [1. 1997. print "list1[0]: ". Like string indices. Tuples and Dictionaries The most basic data structure in Python is the sequence. list3 = ["a". 5 ]. Each element of a sequence is assigned a number . For example: list1 = ['physics'. which can be written as a list of comma-separated values (items) between square brackets. concatenated and so on. and lists can be sliced. 'chemistry'. etc) but the most common ones are lists and tuples which we will see in this tutorial. 5.

1997. print "Value available at index 2 : " print list1[2]. 1997. 68 . del list1[2]. 2000]. Example: #!/usr/bin/python list1 = ['physics'. Note: append() method is discussed in subsequent section. you can use either the del statement if you know exactly which element(s) you are deleting or the remove() method if you do not know. print list1. list1[2] = 2001. and you can add to elements in a list with the append() method: Example: #!/usr/bin/python list1 = ['physics'. 3.Game Scripting with Python – Tim Glasser This will produce following result: list1[0]: physics list2[1:5]: [2. 2000]. 'chemistry'. print "New value available at index 2 : " print list1[2]. This will produce following result: Value available at index 2 : 1997 New value available at index 2 : 2001 Delete List Elements: To remove a list element. 5] Updating Lists: You can update single or multiple elements of lists by giving the slice on the left-hand side of the assignment operator. 'chemistry'. 4.

3] + [4. 2000] Note: remove() method is discussed in subsequent section. 2. indexing and slicing work the same way for lists as they do for strings. 3]: print x. 'Hi!'. This will produce following result: ['physics'. 3]) [1. lists respond to all of the general sequence operations we used on strings in the prior chapter : Python Expression len([1. 2. 'chemistry'. 'SPAM!'] Python Expression L[2] L[-2] 'SPAM!' 'Spam' Results Description Offsets start at zero Negative: count from the right 69 . 6] ['Hi!'. 'Hi!'. In fact. 3. 5. 2.Game Scripting with Python – Tim Glasser print "After deleting value at index 2 : " print list1. Assuming following input: L = ['spam'. 4. 'chemistry'. and Matrixes: Because lists are sequences. 2000] After deleting value at index 2 : ['physics'. 1997. 3] for x in [1. 2. 2. Slicing. not a string. 6] ['Hi!'] * 4 3 in [1. except that the result is a new list. 3 [1. 'Hi!'] True 123 Results Length Concatenation Repetition Membership Iteration Description Indexing. Basic List Operations: Lists respond to the + and * operators much like strings. 'Spam'. they mean concatenation and repetition here too. 5.

list2) Compares elements of both lists.append(obj) Appends object obj to list list. Python includes following list methods SN 1 2 3 4 5 6 7 8 list. list(seq) Converts a tuple into list.extend(seq) Appends the contents of seq to list list.reverse() Reverses objects of list in place Methods with Description 70 .count(obj) Returns count of how many times obj occurs in list list.Game Scripting with Python – Tim Glasser L[1:] ['Spam'.pop(obj=list[-1]) Removes and returns last object or obj from list list.insert(index.remove(obj) Removes object obj from list list. 'SPAM!'] Slicing fetches sections Built-in List Functions & Methods: Python includes following list functions SN 1 2 3 4 5 Function with Description cmp(list1. max(list) Returns item from the list with max value.index(obj) Returns the lowest index in list that obj appears list. len(list) Gives the total length of the list. obj) Inserts object obj into list at offset index list. min(list) Returns item from the list with min value.

'chemistry'. 7 ). For example: tup1 = ('physics'. tuple indices start at 0. 4. 6. tuples are immutable and tuples use parentheses and lists use square brackets. Creating a tuple is as simple as putting different comma-separated values and optionally you can put these comma-separated values between parentheses also.e. tup3 = "a". tup2 = (1. "b". 3. 5 ). 2. and tuples can be sliced. 4. To write a tuple containing a single value you have to include a comma. Tuples are sequences. "d". 3. tup2[1:5] 71 . The empty tuple is written as two parentheses containing nothing: Tup1 = ().Game Scripting with Python – Tim Glasser list. 2000). tup2 = (1. tup1[0] print "tup2[1:5]: ".sort([func]) Sorts objects of list. 2000). 1997. 5. 1997. print "tup1[0]: ". Accessing Values in Tuples: To access values in tuple. concatenated and so on. use compare func if given 9 Tuples A tuple is a sequence of immutable ( not changeable) Python objects. 2. even though there is only one value: Tup1 = (50. 'chemistry'. "c". Like string indices.). use the square brackets for slicing along with the index or indices to obtain value available at that index: Example: #!/usr/bin/python tup1 = ('physics'. The only difference is that tuples can't be changed i. just like lists.

But we able able to take portions of an existing tuples to create a new tuples as follows: Example: #!/usr/bin/python tup1 = (12. just use the del statement: Example: #!/usr/bin/python tup = ('physics'. tup2 = ('abc'. 'xyz'). 4. # Following action is not valid for tuples # tup1 += tup2. 34. nothing wrong with putting together another tuple with the undesired elements discarded. 2000).56). This will produce following result: (12. 'abc'.56. There is. del tup. # So let's create a new tuple as follows tup3 = tup1 + tup2.Game Scripting with Python – Tim Glasser This will produce following result: tup1[0]: physics tup2[1:5]: [2. To explicitly remove an entire tuple. print "After deleting tup : " 72 . print tup3. print tup. 34. 'xyz') Delete Tuple Elements: Removing individual tuple elements is not possible. 1997. 3. 'chemistry'. of course. 5] Updating Tuples: Tuples are immutable which means you cannot update them or change values of tuple elements.

NameError: name 'tup' is not defined Basic Tuples Operations: Tuples respond to the + and * operators much like strings. 3) + (4. 3. not a string. 2. 'SPAM!') Python Expression L[2] L[-2] 'SPAM!' 'Spam' Results Description Offsets start at zero Negative: count from the 73 . 3) for x in (1. they mean concatenation and repetition here too. Note an exception raised. Assuming following input: L = ('spam'. 5. tuples respond to all of the general sequence operations we used on strings in the prior chapter : Python Expression len((1. 3)) (1. line 9. 3 (1. except that the result is a new tuple. 6) ['Hi!'] * 4 3 in (1. 'Hi!'. 3): print x. 6) ('Hi!'. this is because after del tup tuple does not exist any more: ('physics'. in <module> print tup.py". 'Hi!'. 4. 2. 'Hi!') True 123 Results Length Concatenation Repetition Membership Iteration Description Indexing. 1997. 2000) After deleting tup : Traceback (most recent call last): File "test. and Matrixes: Because tuples are sequences.Game Scripting with Python – Tim Glasser print tup. This will produce following result. Slicing. indexing and slicing work the same way for tuples as they do for strings. 5. 'chemistry'. 'Spam'. 2. 2. In fact. 2.

as indicated in these short examples: #!/usr/bin/python print 'abc'. x. -4. default to tuples. ['Spam'. y = 1. 18+6. 'xyz'.e. y : 1 2 Built-in Tuple Functions: Python includes following tuple functions SN 1 2 3 4 5 Function with Description cmp(tuple1.6j. i. 'SPAM!'] Slicing fetches sections 74 . print var.24e+93 (18+6..y. min(tuple) Returns item from the tuple with min value. print "Value of x . x. parentheses for tuples. tuple(seq) Converts a list into tuple. comma-separated.6j) xyz Value of x .24e93. etc.. tuple2) Compares elements of both tuples. brackets for lists. len(tuple) Gives the total length of the tuple. 2. y : ". written without identifying symbols. This will reduce following result: abc -4.Game Scripting with Python – Tim Glasser right L[1:] No Enclosing Delimiters: Any set of multiple objects. max(tuple) Returns item from the tuple with max value.

like this: {}. dict['Age']. print "dict['Name']: ". but the keys must be of an immutable data type such as strings. dict['Name']. the items are separated by commas. and the whole thing is enclosed in curly braces.Game Scripting with Python – Tim Glasser Dictionaries A dictionary is mutable and is another container type that can store any number of Python objects. Dictionaries consist of pairs (called items) of keys and their corresponding values. 'Class': 'First'}. 'Beth': '9102'. 'Cecil': '3258'} You can create dictionary in the following way as well: dict1 = { 'abc': 456 }. 98. print "dict['Age']: ".6: 37 }. This will produce following result: 75 . Keys are unique within a dictionary while values may not be. including other container types. The general syntax of a dictionary is as follows: Dict = {'Alice': '2341'. Accessing Values in Dictionary: To access dictionary elements. 'Age': 7. The values of a dictionary can be of any type. you use the familiar square brackets along with the key to obtain its value: Example: #!/usr/bin/python dict = {'Name': 'Zara'. An empty dictionary without any items is written with just two curly braces. dict2 = { 'abc': 123. numbers. Python dictionaries are also known as associative arrays or hash tables. or tuples. Each key is separated from its value by a colon (:).

in <module> print "dict['Alice']: ".. dict['Alice']. This will produce following result: dict['Age']: 8 dict['School']: DPS School Delete Dictionary Elements: 76 . # Add new entry print "dict['Age']: ". dict['Alice']. 'Age': 7. KeyError: 'Alice' Updating Dictionary: You can update a dictionary by adding a new entry or item (i. 'Class': 'First'}. line 4.py". dict['Age'] = 8. a key-value pair). dict['School']. dict['Age']. modifying an existing entry.e. print "dict['School']: ". we get an error as follows: #!/usr/bin/python dict = {'Name': 'Zara'. or deleting an existing entry as shown below: Example: #!/usr/bin/python dict = {'Name': 'Zara'. 'Class': 'First'}.Game Scripting with Python – Tim Glasser dict['Name']: Zara dict['Age']: 7 If we attempt to access a data item with a key which is not part of the dictionary. print "dict['Alice']: ". # update existing entry dict['School'] = "DPS School". 'Age': 7. This will produce following result: dict['Zara']: Traceback (most recent call last): File "test.

the last assignment wins. same is not true for the keys. dict['School']. You can also delete entire dictionary in a single operation. This will produce following result. Properties of Dictionary Keys: Dictionary values have no restrictions. line 8.clear(). del dict['Name']. 'Class': 'First'}. When duplicate keys encountered during assignment. just use the del statement: Example: #!/usr/bin/python dict = {'Name': 'Zara'. # remove entry with key 'Name' dict. either standard objects or user-defined objects. print "dict['School']: ". Example: #!/usr/bin/python 77 . However. To explicitly remove an entire dictionary. Note an exception raised. There are two important points to remember about dictionary keys: (a) More than one entry per key not allowed. in <module> print "dict['Age']: ". Which means no duplicate key is allowed. this is because after del dict dictionary does not exist any more: dict['Age']: Traceback (most recent call last): File "test.Game Scripting with Python – Tim Glasser You can either remove individual dictionary elements or clear the entire contents of a dictionary.py". dict['Age']. # delete entire dictionary print "dict['Age']: ". # remove all entries in dict del dict . dict['Age']. TypeError: 'type' object is unsubscriptable Note: del() method is discussed in subsequent section. 'Age': 7. They can be any arbitrary Python object.

'Age': 7}. in <module> dict = {['Name']: 'Zara'. dict['Name']. Note an exception raised: Traceback (most recent call last): File "test. dict2) Compares elements of both dict. Which means you can use strings. This will produce following result: Dict['Name']: Manni (b) Keys must be immutable. This will produce following result. Example: #!/usr/bin/python dict = {['Name']: 'Zara'.Game Scripting with Python – Tim Glasser dict = {'Name': 'Zara'. This would be equal to the number of items in the dictionary. 'Age': 7}. If passed variable is dictionary then it would return a dictionary type. or tuples as dictionary keys but something like ['key'] is not allowed. line 3. len(dict) Gives the total length of the dictionary. TypeError: list objects are unhashable Built-in Dictionary Functions & Methods: Python includes following dictionary functions SN 1 Function with Description cmp(dict1. print "dict['Name']: ".py". str(dict) Produces a printable string representation of a dictionary type(variable) Returns the type of the passed variable. dict['Name']. numbers. 'Age': 7. 2 3 4 78 . print "dict['Name']: ". 'Name': 'Manni'}.

update(dict2) Adds dictionary dict2's key-values pairs to dict dict. dict.copy() Returns a shallow copy of dictionary dict dict. Add "John Smith" and "Mary Miller" at the beginning of the list (by using "+").values() Returns list of dictionary dict2's values Exercises 1) Create a list that contains the names of 5 students of this class.clear() Removes all elements of dictionary dict dict. Print the original list and the reverse list. Ask the user to input a name and return the appropriate phone number.get(key. Print the list. 3) Create a Dictionary of names and phone numbers. 2) Continue with the script from 1.Game Scripting with Python – Tim Glasser Python includes following dictionary methods SN 1 2 2 3 4 5 6 7 8 9 Methods with Description dict. simply create the list. default=None) For key key. Check whether that name is in the list: if it is then delete it from the list. Ask a user to input a number. 79 . (Do not ask for input to do that.keys() Returns list of dictionary dict's keys dict. but will set dict[key]=default if key is not already in dict dict.) Print the list.setdefault(key. returns value or default if key not in dictionary dict. Create a copy of the list in reverse order. Print the list. Print the list. Print the name that has that number as index. Ask a user to type a name. default=None) Similar to get(). false otherwise dict. Ask the user to input one more name and append it to the list.has_key(key) Returns true if key in dictionary dict. value) tuple pairs dict.fromkeys() Create a new dictionary with keys from seq and values set to value.1): Print the list.items() Returns a list of dict's (key. Remove the last name from the list. Otherwise add it at the end.

Game Scripting with Python – Tim Glasser Week 7 – Object Oriented Programming – Start Pygame Here Exercises: 1) Create a board and a counter class which have a visual draw method using Pygame 2) How should the board and counters be linked together? 3) Create a sprite with animation and gamepad comtrol 4) Create a background tile set 16*16 loading from a text file 5) Integrate the sprite and background 6) Add an enemy sprite 80 .

separated by commas. This function converts the expressions you pass it to a string and writes the result to standard output as follows: #!/usr/bin/python print "Python is really a great language.Game Scripting with Python – Tim Glasser Week 8 – Input and Output This chapter will cover all the basic I/O functions available in Python. str This would prompt you to enter any string and it would display same string on the screen. When I typed "Hello Python!".". which by default comes from the your keyboard. isn't it? Reading Keyboard Input: Python provides two built-in functions to read a line of text from standard input. print "Received input is : ". Printing to the Screen: The simplest way to produce output is using the print statement where you can pass zero or more expressions. it output is like this: Enter your input: Hello Python Received input is : Hello Python The input Function: 81 . This would produce following result on your standard screen: Python is really a great language. These functions are: raw_input input The raw_input Function: The raw_input([prompt]) function reads one line from standard input and returns it as a string (removing the trailing newline): #!/usr/bin/python str = raw_input("Enter your input: "). "isn't it?".

Game Scripting with Python – Tim Glasser The input([prompt]) function is equivalent to raw_input. access_mode: The access_mode determines the mode in which the file has to be opened ie. Here is a list of the different modes of opening a file: 82 . read. you have been reading and writing to the standard input and output. Syntax: file object = open(file_name [. This is optional parameter and the default file access mode is read (r) buffering: If the buffering value is set to 0. A complete list of possible values is given below in the table. The open Function: Before you can read or write a file. no buffering will take place. then buffering action will be performed with the indicated buffer size. except that it assumes the input is a valid Python expression and returns the evaluated result to you: #!/usr/bin/python str = raw_input("Enter your input: "). str This would produce following result against the entered input: Enter your input: [x*5 for x in range(2. If you specify the buffering value as an integer greater than 1. This function creates a file object which would be utilized to call other support methods associated with it. 30. You can do your most of the file manipulation using a file object. buffering]) Here is paramters detail: file_name: The file_name argument is a string value that contains the name of the file that you want to access.2)] Recieved input is : [10. access_mode][.10. 40] Opening and Closing Files: Until now. This is optional paramter. Now we will see how to play with actual data files. Python provides basic functions and methods necessary to manipulate files by default. 20. print "Received input is : ". write append etc. If the buffering value is 1. you have to open it using Python's built-in open() function. line buffering will be performed while accessing a file.

This is the default mode. The file pointer is at the end of the file if the file exists. creates a new file for reading and writing. Overwrites the existing file if the file exists. you can get various information related to that file. it creates a new file for writing. If the file does not exist. The file pointer is placed at the beginning of the file. Overwrites the existing file if the file exists. Opens a file for both appending and reading in binary format. Opens a file for appending. If the file does not exist. the file is in the append mode. The file pointer is placed at the beginning of the file. Here is a list of all attributes related to file object: 83 . the file is in the append mode. Opens a file for reading only in binary format. Opens a file for appending in binary format. it creates a new file for reading and writing.Game Scripting with Python – Tim Glasser Modes r rb r+ rb+ w wb w+ Description Opens a file for reading only. If the file does not exist. If the file does not exist. Opens a file for writing only in binary format. That is. The file opens in the append mode. If the file does not exist. The file opens in the append mode. If the file does not exist. The file pointer will be at the beginning of the file. Opens a file for both reading and writing in binary format. Opens a file for both appending and reading. Overwrites the file if the file exists. That is. creates a new file for writing. This is the default mode. The file pointer is at the end of the file if the file exists. wb+ a ab a+ ab+ The file object atrributes: Once a file is opened and you have one file object. The file pointer is at the end of the file if the file exists. creates a new file for writing. Opens a file for writing only. The file pointer is at the end of the file if the file exists. it creates a new file for writing. Opens a file for both reading and writing. Opens a file for both writing and reading. it creates a new file for reading and writing. The file pointer will be at the beginning of the file. If the file does not exist. If the file does not exist. Overwrites the file if the file exists. creates a new file for reading and writing. Opens a file for both writing and reading in binary format.

fo. fo. Python automatically closes a file when the reference object of a file is reassigned to another file. true otherwise.Game Scripting with Python – Tim Glasser Attribute file. "wb") print "Name of the file: ". 84 . fo. fo.txt". Returns false if space explicitly required with print.name print "Closed or not : ".mode print "Softspace flag : ".closed print "Opening mode : ". false otherwise.closed file. fo.name Description Returns true if file is closed. Returns name of the file. Syntax: fileObject. after which no more writing can be done.softspace Example: #!/usr/bin/python # Open a file fo = open("foo.txt".name file.softspace This would produce following result: Name of the file: foo. Example: #!/usr/bin/python # Open a file fo = open("foo. "wb") print "Name of the file: ".txt Closed or not : False Opening mode : wb Softspace flag : 0 The close() Method: The close() method of a file object flushes any unwritten information and closes the file object.mode file. It is a good practice to use the close() method to close a file.close(). Returns access mode with which file was opened.

The write() Method: The write() method writes any string to an open file.txt file and would write given content in that file and finally it would close that file.txt Reading and Writing Files: The file object provides a set of access methods to make our lives easier. The write() method does not add a newline character ('\n') to the end of the string: Syntax: fileObject. Yeah its great!! 85 .write(string). We would see how to use read() and write() methods to read and write files.close() This would produce following result: Name of the file: foo. If you would open this file.txt".\nYeah its great!!\n").Game Scripting with Python – Tim Glasser # Close opend file fo. "wb") fo. it would have following content Python is a great language.write( "Python is a great language. Here passed parameter is the content to be written into the opend file. # Close opend file fo. It is important to note that Python strings can have binary data and not just text. Example: #!/usr/bin/python # Open a file fo = open("foo.close() The above method would create foo.

"r+") str = fo. it means use the beginning of the file as the reference position and 1 means use the current position as the reference position and if it is set to 2 then the end of the file would be taken as the reference position. Here passed parameter is the number of bytes to be read from the opend file.txt".close() This would produce following result: Read String is : Python is File Positions: The tell() method tells you the current position within the file in other words.txt which we have created above. from]) method changes the current file position. print "Read String is : ". It is important to note that Python strings can have binary data and not just text. Example: Let's take a file foo. Example: 86 .read([count]).Game Scripting with Python – Tim Glasser The read() Method: The read() method read a string from an open file. The from argument specifies the reference position from where the bytes are to be moved. Syntax: fileObject. may be until the end of file. The offset argument indicates the number of bytes to be moved. str # Close opend file fo. This method starts reading from the beginning of the file and if count is missing then it tries to read as much as possible. the next read or write will occur at that many bytes from the beginning of the file: The seek(offset[.read(10). If from is set to 0. #!/usr/bin/python # Open a file fo = open("foo.

rename(current_file_name. str # Check current position position = fo. print "Again read String is : ".tell(). position # Reposition pointer at the beginning once again position = fo. The rename() Method: The rename() method takes two arguments.close() This would produce following result: Read String is : Python is Current file position : 10 Again read String is : Python is Renaming and Deleting Files: Python os module provides methods that help you perform file-processing operations. such as renaming and deleting files. the current filename and the new filename.Game Scripting with Python – Tim Glasser Let's take a file foo.txt: 87 .seek(0.read(10). str = fo. "r+") str = fo.txt which we have created above.read(10). 0). #!/usr/bin/python # Open a file fo = open("foo. new_file_name) Example: Following is the example to rename an existing file test1. Syntax: os. str # Close opend file fo. print "Current file position : ". print "Read String is : ". To use this module you need to import it first and then you can all any related functions.txt".

txt os.txt") Exercises: 1) Ask the user for a Python script file.txt: #!/usr/bin/python import os # Delete file test2. Syntax: os. 2) Create the 1-12 times tables and format the output in to a file named after the first argument to the script 88 .Game Scripting with Python – Tim Glasser #!/usr/bin/python import os # Rename a file from test1. open the file and report how many lines and how many words are in the file.txt" ) The delete() Method: You can use the delete() method to delete files by supplying the name of the file to be deleted as the argument.delete("text2.rename( "test1. Don’t forget to close the file.txt".txt to test2.delete(file_name) Example: Following is the example to delete an existing file test2. "test2.txt os.

import has the following syntax: import module1[. Asearch path is a list of directories that the interpreter searches before importing a module.. Simply. A module is a Python object with arbitrarily named attributes that you can bind and reference. a module is a file consisting of Python code.Game Scripting with Python – Tim Glasser Week 9 Modules A module allows you to logically organize your Python code.. par return The import Statement: You can use any Python source file as a module by executing an import statement in some other Python source file. module2[.py. classes. Grouping related code into a module makes the code easier to understand and use.print_func("Zara") 89 .py. Example: The Python code for a module named aname normally resides in a file named aname. hello. Example: To import the module hello. A module can define functions..py def print_func( par ): print "Hello : ". and variables. you need to put the following command at the top of the script: #!/usr/bin/python # Import module hello import hello # Now you can call defined function that module as follows hellp. moduleN] When the interpreter encounters an import statement. Here's an example of a simple module. it imports the module if the module is present in the search path.

Locating Modules: When you import a module. name2[..import Statement Python's from statement lets you import specific attributes from a module into the current namespace: Syntax: from modname import name1[. . this statement should be used sparingly.Game Scripting with Python – Tim Glasser This would produce following result: Hello : Zara A module is loaded only once. however.. The from. regardless of the number of times it is imported.. to import the function fibonacci from the module fib. The from.. the Python interpreter searches for the module in the following sequences: 90 . nameN]] Example: For example. use the following statement: from fib import fibonacci This statement does not import the entire module fib into the current namespace..import * Statement: It is also possible to import all names from a module into the current namespace by using the following import statement: from modname import * This provides an easy way to import all the items from a module into the current namespace. This prevents the module execution from happening over and over again if multiple imports occur.. it just introduces the item fibonacci from the module fib into the global symbol table of the importing module.

path variable. you must first use the global statement.Game Scripting with Python – Tim Glasser The current directory. Therefore. And here is a typical PYTHONPATH from a UNIX system: set PYTHONPATH=/usr/local/lib/python Namespaces and Scoping: Variables are names (identifiers) that map to objects. A Python statement can access variables in a local namespace and in the global namespace. Python checks the default path. PYTHONPATH. Each function has its own local namespace. If a local and a global variable have the same name. If the module isn't found. this default path is normally /usr/local/lib/python/. The PYTHONPATH Variable: The PYTHONPATH is an environment variable. and the installationdependent default. 91 . On UNIX. Python makes educated guesses on whether variables are local or global. Python stops searching the local namespace for the variable. It assumes that any variable assigned a value in a function is local. Python then searches each directory in the shell variable PYTHONPATH. The module search path is stored in the system module sys as the sys. A namespace is a dictionary of variable names (keys) and their corresponding objects (values).path variable contains the current directory. The syntax of PYTHONPATH is the same as that of the shell variable PATH. Class methods follow the same scoping rule as ordinary functions. Here is a typical PYTHONPATH from a Windows system: set PYTHONPATH=c:\python20\lib. consisting of a list of directories. The statement global VarName tells Python that VarName is a global variable. in order to assign a value to a global variable within a function. The sys. If all else fails. the local variable shadows the global variable.

'atan2'. 'sin'. 'radians'. 'pi'. 'hypot'. 'fmod'. therefor Python assumes Money is a local variable. so an UnboundLocalError is the result. 'modf'.Game Scripting with Python – Tim Glasser For example. 'atan'. we define a variable Money in the global namespace. 'log10'. 'ldexp'. 'floor'. 'tanh'] 92 . 'sqrt'. Example: #!/usr/bin/python # Import built-in module math import math content = dir(math) print content. 'frexp'. 'acos'. we access the value of the local variable Money before setting it. 'asin'. 'tan'. 'exp'. '__file__'. 'cosh'. Uncommenting the global statement fixes the problem. 'cos'. '__name__'. However. #!/usr/bin/python Money = 2000 def AddMoney(): # Uncomment the following line to fix the code: # global Money Money = Money + 1 print Money AddMoney() print Money The dir( ) Function: The dir() built-in function returns a sorted list of strings containing the names defined by a module. 'pow'. 'log'. 'degrees'. The list contains the names of all the modules. we assign Money a value . 'e'. 'sinh'. 'ceil'. This would produce following result: ['__doc__'. Within the function Money. and functions that are defined in a module. 'fabs'. variables.

Game Scripting with Python – Tim Glasser Here the special string variable __name__ is the module's name. do the following: reload(hello) 93 . the code in the top-level portion of a module is executed only once. you can use the reload() function. The reload() Function: When the module is imported into a script. it will return all the names that can be accessed locally from that function. it will return all the names that can be accessed globally from that function. and __file__ is the filename from which the module was loaded. The reload() function imports a previously imported module again. If locals() is called from within a function. Therefore. Therefore. If globals() is called from within a function. names can be extracted using the keys() function. The return type of both these functions is dictionary. Syntax: The syntax of the reload() function is this: reload(module_name) Here module_name is the name of the module you want to reload and not the string containing the module name. For example to re-load hello module. The globals() and locals() Functions: The globals() and locals() functions can be used to return the names in the global and local namespaces depending on the location from where they are called. if you want to reexecute the top-level code in a module.

. Here are few important points above the above mentioned syntax: 94 .. then execute this block.....Game Scripting with Python – Tim Glasser Week 10 – Handling Errors Python provides two very important features to handle any unexpected error in your Python programs and to add debugging capabilities in them: Exception Handling: This would be covered in this tutorial.. . when a Python script encounters a situation that it can't cope with.else blocks: try: Do you operations here. followed by a block of code which handles the problem as elegantly as possible. Assertions: This would be covered in another tutorial. except ExceptionI: If there is ExceptionI.... In general. it must either handle the exception immediately otherwise it would terminate and come out...except... else: If there is no exception then execute this block... then execute this block. ... Handling an exception: If you have some suspicious code that may raise an exception.. Syntax: Here is simple syntax of try.. include an except: statement... What is Exception? An exception is an event. When a Python script raises an exception.. After the try: block......... which occurs during the execution of a program.... it raises an exception....... except ExceptionII: If there is ExceptionII...... An exception is a Python object that represents an error.. you can defend your program by placing the suspicious code in a try: block. which then disrupts the normal flow of the program's instructions..

This is useful when the try block contains statements that may throw different types of exceptions. "w") fh. The code in the elseblock executes if the code in the try: block does not raise an exception.Game Scripting with Python – Tim Glasser A single try statement can have multiple except statements. You can also provide a generic except clause. The else-block is a good place for code that does not need the try: block's protection. you can include an else-clause. which handles any exception.write("This is my test file for exception handling!!") except IOError: print "Error: can\'t find file or read data" else: print "Written content in the file successfully" fh.write("This is my test file for exception handling!!") except IOError: print "Error: can\'t find file or read data" else: print "Written content in the file successfully" This will produce following result: 95 . After the except clause(s). Example: Here is simple example which opens a file and writes the content in the file and comes out gracefully because there is no problem at all: #!/usr/bin/python try: fh = open("testfile".close() This will produce following result: Written content in the file successfully Example: Here is one more simple example which tries to open a file where you do not have permission to write in the file so it raises an exception: #!/usr/bin/python try: fh = open("testfile". "w") fh.

...... except(Exception1[.. though..... then execute this block....... ..... The except clause with multiple exceptions: You can also use the same except statement to handle multiple exceptions as follows: try: Do you operations here.. The finally block is a place to put any code that must execute.. . except: If there is any exception... This kind of a try-except statement catches all the exceptions that occur.Game Scripting with Python – Tim Glasser Error: can't find file or read data The except clause with no exceptions: You can also use the except statement with no exceptions defined as follows: try: Do you operations here... Exception2[.. else: If there is no exception then execute this block............. ...... Standard Exceptions: Here is a list standard Exceptions available in Python: Standard Exceptions The try-finally clause: You can use a finally: block along with a try: block. because it catches all exceptions but does not make the programmer identify the root cause of the problem that may occur.... . else: If there is no exception then execute this block..........ExceptionN]]]): If there is any exception from the given exception list... whether the try-block raised an exception or not................... then execute this block.......... The syntax of the try-finally statement is this: 96 .. Using this kind of try-except statement is not considered a good programming practice.

... the execution immediately passes to the finally block......... this may be skipped.. After all the statements in the finally block are executed.write("This is my test file for exception handling!!") finally: print "Error: can\'t find file or read data" If you do not have permission to open the file in writing mode then this will produce following result: Error: can't find file or read data Same example can be written more cleanly as follows: #!/usr/bin/python try: fh = open("testfile". the exception is raised again and is handled in the except statements if present in the next higher layer of the try-except statement.. Example: #!/usr/bin/python try: fh = open("testfile"... .. You can not use else clause as well along with a finally clause.. "w") fh. "w") try: fh.Game Scripting with Python – Tim Glasser try: Do you operations here..... or a finally clause.. 97 .... . but not both...... Note that you can provide except clause(s)......close() except IOError: print "Error: can\'t find file or read data" When an exception is thrown in the try block...write("This is my test file for exception handling!!") finally: fh... finally: This would always be executed.. Due to any exception...

py. Artificial intelligence (or AI) is a computer program that can intelligently respond to the player's moves. We will see that the artificial intelligence that plays Tic Tac Toe is really just several lines of code. Then run the game by pressing F5. | | O | | | | ----------| | | | | | ----------| | | | | | What is your next move? (1-9) 3 | | O | | | | ----------| | | | | | ----------| | O | | X | | What is your next move? (1-9) 4 | | O | | O | | ----------| | X | | 98 . type in this source code and save it as tictactoe.Game Scripting with Python – Tim Glasser Appendix A – Designing and Implementing a Tic Tac Toe Game We will now create a Tic Tac Toe game where the player plays against a simple artificial intelligence. So in a new file editor window. Sample Run Welcome to Tic Tac Toe! Do you want to be X or O? X The computer will go first. This game doesn't introduce any complicated new concepts.

randomly choose who goes first. Here is what a flow chart of this game could look like: 99 . Do you want to play again? (yes or no) no Designing the Program Tic Tac Toe is a very easy and short game to play on paper. and then let the player and computer take turns making moves on the board. we'll let the player choose if they want to be X or O. In our Tic Tac Toe computer game.Game Scripting with Python – Tim Glasser | | ----------| | O | | X | | What is your next move? (1-9) 5 | | O | O | O | | ----------| | X | X | | | ----------| | O | | X | | The computer has beaten you! You lose.

O. The player has an extra box for drawing the board because the computer doesn't need the board printed on the screen. First. The ten strings will represent each of the nine positions on the board (and we will ignore one of our strings). 'O' for the O player.Game Scripting with Python – Tim Glasser You can see a lot of the boxes on the left side of the chart are what happens during the player's turn. we ask the player if they want to play again. The strings will either be 'X' for the X player. or blank space). board[5] would be the very 100 . If either the computer or player ties or wins the game. we check if they won or caused a tie. and then the game switches turns. or a space string ' ' to mark a spot on the board where no one has marked yet. we will mirror the numbers on the keypad of our keyboard. we will just ignore the string at index 0 in our list. The right side of the chart shows what happens on the computer's turn. After the player or computer makes a move.) So if we had a list with ten strings named board. To make it easier to remember which index in the list is for which piece. then board[7] would be the topleft square on the board (either an X. (Because there is no 0 on the keypad. we need to figure out how we are going to represent the board as a variable. We are going to represent the Tic Tac Toe board as a list of ten strings.

go to step 3. If there is. # Tic Tac Toe 2. 5. 2. see if there is a move the computer can make that will win the game. 3. 101 . or 9) are free. 3. An algorithm is a series of instructions to compute something. import random A comment and importing the random module so we can use the randint() function in our game. we should move there to block the player. First. because if we have reached step 5 the side spaces are the only spaces left.Game Scripting with Python – Tim Glasser center. we will label three types of spaces on the Tic Tac Toe board: corners. sides. If so. Here is a chart of what each space is: The AI for this game will follow a simple algorithm. go to step 2. take that move. Our algorithm will have the following steps: 1. Otherwise. There are no more steps. then go to step 4. If there is. 6. Otherwise. Check if the center is free. and the center. (We always want to take a corner piece instead of the center or a side piece. See if there is a move the player can make that will cause the computer to lose the game.) If no corner piece is free. then go to step 5. move there. 4. 7. Our Tic Tac Toe AI's algorithm will determine which is the best place to move. Game AI Just to be clear. Source Code 1. When the player types in which place they want to move. 3. 4. they will type a number from 1 to 9. Move on any of the side pieces (spaces 2. Check if any of the corner spaces (spaces 1. or 8). If it isn't.

Just as an example. ' '. print ' | |' 16. 'X'. print ' ' + board[4] + ' | ' + board[5] + ' | ' + board[6] 15. 'X'. print ' | |' 18. ' '. ' '. 'O'. def drawBoard(board): 6. otherwise the board will look funny when it is printed on the screen. ' '. # "board" is a list of 10 strings representing the board (ignore index 0) 9. print ' | |' 12. ' '. ' '. 8. print ' | |' 10.Game Scripting with Python – Tim Glasser 5. ' '. print '-----------' 13. here are some values that the board parameter could have (on the left) and what the drawBoard() function would print out: drawBoard(board) output | | X | | O | | ----------| | X | O | | | ----------| | | | | | | | | | | | ----------| | | X | board data structure [' '. print ' ' + board[1] + ' | ' + board[2] + ' | ' + board[3] 19. ' '] 102 . 'X'. 'O'. 7. print ' ' + board[7] + ' | ' + board[8] + ' | ' + board[9] 11. ' '. Be sure to get the spacing right in the strings that are printed. 'O'] [' '. print ' | |' This function will print out the game board. print '-----------' 17. # This function prints out the board that it was passed. ' '. print ' | |' 14. ' '. Many of our functions will work by passing the board as a list of ten strings to our functions. marked as directed by the board parameter. 'O'.

'X'. 'X'] Copyright 2008. 'X'. ' '] [' '. ' '. 'X'. 'X'. 'X'. 'X'. ' '. ' '.Game Scripting with Python – Tim Glasser | | ----------| | O | O | | | | | | | | | ----------| | | | | | ----------| | | | | | | | X | X | X | | ----------| | X | X | X | | ----------| | X | X | X | | [' '. ' '. 'X'. 2009 © by Albert Sweigart "Invent Your Own Computer Games with Python" is licensed under a Creative Commons Attribution-Noncommercial-Share Alike 3. ' '. ' '. ' '. 103 . ' '.0 United States License. 'X'.

current pedal cadence. Each discussion focuses on how these concepts relate to the real world. off. but your desktop radio might have additional states (on. breed. Software objects are often used to model the real-world objects that you find in everyday life. Look around right now and you'll find many examples of real-world objects: your dog.Game Scripting with Python – Tim Glasser Appendix B Object Oriented Programming Objectives • Understand the basic Object Oriented principles. turn off). in turn. your desk. your desktop lamp may have only two possible states (on and off) and two possible behaviors (turn on. What Is an Object? Objects are key to understanding object-oriented technology. decrease volume. This lesson explains how state and behavior are represented within an object. For each object that you see. introduces the concept of data encapsulation. ask yourself two questions: "What possible states can this object be in?" and "What possible behavior can this object perform?". As you do. 104 . scan. Make sure to write down your observations. changing pedal cadence. you will need to learn a few basic concepts before you can begin writing any code. hungry) and behavior (barking. fetching. applying brakes). and interfaces. and explains the benefits of designing your software in this manner. This lesson will introduce you to objects. and tune). which is composed of: • Understanding the idea of a component • Understanding Objects • Understanding Classes • Understandinding Inheritance • Understanding the Interface and Encapsulation Object-Oriented Programming Concepts If you've never used an object-oriented programming language before. current volume. wagging tail). you'll notice that real-world objects vary in complexity. color. classes. seek. turn off. inheritance. Real-world objects share two characteristics: They all have state and behavior. What Is an Object? An object is a software bundle of related state and behavior. Take a minute right now to observe the real-world objects that are in your immediate area. You may also notice that some objects. increase volume. Bicycles also have state (current gear. while simultaneously providing an introduction to the syntax of the C++ programming language. Dogs have state (name. your bicycle. Identifying the state and behavior for real-world objects is a great way to begin thinking in terms of objectoriented programming. current speed) and behavior (changing gear. your television set. current station) and behavior (turn on.

These real-world observations all translate into the world of object-oriented programming. the object remains in control of how the outside world is allowed to use it. and current gear) and providing methods for changing that state. An object stores its state in fields (variables in some programming languages) and exposes its behavior through methods (functions in some programming languages). a method to change gears could reject any value that is less than 1 or greater than 6. Software objects are conceptually similar to real-world objects: they too consist of state and related behavior. current pedal cadence. if the bicycle only has 6 gears. Consider a bicycle. 105 . A software object.Game Scripting with Python – Tim Glasser will also contain other objects. By attributing state (current speed. for example: A bicycle modeled as a software object. For example. Hiding internal state and requiring all interaction to be performed through an object's methods is known as data encapsulation — a fundamental principle of object-oriented programming. Methods operate on an object's internal state and serve as the primary mechanism for object-to-object communication.

This section defines a class that models the state and behavior of a real-world object. you replace it. Each bicycle was built from the same set of blueprints and therefore contains the same components. } void speedUp(int increment) { speed = speed + increment. Information-hiding: By interacting only with an object's methods. In the real world. The following Bicycle class is one possible implementation of a bicycle: class Bicycle { int cadence = 0. the details of its internal implementation remain hidden from the outside world. including: 1. int speed = 0. If a bolt breaks. } void changeGear(int newValue) { gear = newValue. you can use that object in your program. There may be thousands of other bicycles in existence. showing how even simple classes can cleanly model state and behavior. Debugging ease: If a particular object turns out to be problematic. This is analogous to fixing mechanical problems in the real world. you can simply remove it from your application and plug in a different object as its replacement. int gear = 1. 3. Once created. A class is the blueprint from which individual objects are created. task-specific objects. Code re-use: If an object already exists (perhaps written by another software developer). This allows specialists to implement/test/debug complex. void changeCadence(int newValue) { cadence = newValue. we say that your bicycle is an instance of the class of objects known as bicycles. Modularity: The source code for an object can be written and maintained independently of the source code for other objects. 4. } 106 . not the entire machine. What Is a Class? A class is a blueprint or prototype from which objects are created. 2. which you can then trust to run in your own code.Game Scripting with Python – Tim Glasser Bundling code into individual software objects provides a number of benefits. It intentionally focuses on the basics. In object-oriented terms. an object can be easily passed around inside the system. you'll often find many individual objects all of the same kind. all of the same make and model.

} } The design of this class is based on the previous discussion of bicycle objects. bike2.changeCadence(50).changeCadence(50). changeGear.changeGear(3).speedUp(10).speedUp(10). bike1. and the methods (changeCadence. speedUp etc.out.changeGear(2). } void printStates() { System. The responsibility of creating and using new Bicycle objects belongs to some other class in your application. speed. Bicycle bike2 = new Bicycle(). This section explains how classes inherit state and behavior from their 107 .changeGear(2). bike2. bike1. bike2.printStates(). bike2. bike1. bike2. } The output of this test prints the ending pedal cadence. Here's a BicycleDemo class that creates two separate Bicycle objects and invokes their methods: void main(String[] args) { // Create two different Bicycle objects Bicycle bike1 = new Bicycle(). it's just the blueprint for bicycles that might be used in an application. speed.printStates().decrement.changeCadence(40). That's because it's not a complete application.Game Scripting with Python – Tim Glasser void applyBrakes(int decrement) { speed = speed . You may have noticed that the Bicycle class does not contain a main method. and gear represent the object's state.) define its interaction with the outside world. bike2.speedUp(10).println("cadence:"+cadence+" speed:"+speed+" gear:"+gear). bike2. and gear for the two bicycles: cadence:50 speed:10 gear:2 cadence:40 speed:20 gear:3 Inheritance Inheritance provides a powerful and natural mechanism for organizing and structuring your software. // Invoke methods on those objects bike1. The fields cadence.

each class is allowed to have one direct superclass. followed by the name of the class to inherit from: class MountainBike :public Bicycle { // new fields and methods defining a mountain bike would go here } This gives MountainBike all the same fields and methods as Bicycle. current pedal cadence. What Is Inheritance? Different kinds of objects often have a certain amount in common with each other. and tandem bikes. road bikes. and TandemBike.Game Scripting with Python – Tim Glasser superclasses. road bikes have drop handlebars. In this example. This makes code for your 108 . At the beginning of your class declaration. and explains how to derive one class from another using the simple syntax provided by the C++ programming language. yet allows its code to focus exclusively on the features that make it unique. In the Java programming language. all share the characteristics of bicycles (current speed. The syntax for creating a subclass is simple. Bicycle now becomes the superclass of MountainBike. Object-oriented programming allows classes to inherit commonly used state and behavior from other classes. and each superclass has the potential for an unlimited number of subclasses: A hierarchy of bicycle classes. Mountain bikes. giving them a lower gear ratio. RoadBike. Yet each also defines additional features that make them different: tandem bicycles have two seats and two sets of handlebars. use the extends keyword. for example. some mountain bikes have an additional chain ring. current gear).

for example). for example. Methods form the object's interface with the outside world. You press the "power" button to turn the television on and off. When a class implements an interface. since that code will not appear in the source file of each subclass. void changeGear(int newValue){}. If your class claims to implement an interface. might appear as follows: class IBicycle { void changeCadence(int newValue){}. it promises to provide the behavior published by that interface. As you've already learned. the name of your class would change (to ACMEBicycle. } Note that this is an abstract class. objects define their interaction with the outside world through the methods that they expose. if specified as an interface. 109 . A bicycle's behavior. the buttons on the front of your television set. void applyBrakes(int decrement){}. are the interface between you and the electrical wiring on the other side of its plastic casing. all methods defined by that interface must appear in its source code before the class will successfully compile.Game Scripting with Python – Tim Glasser subclasses easy to read. Interfaces form a contract between the class and the outside world. Why? To implement this interface. you must take care to properly document the state and behavior that each superclass defines. In its most common form. and this contract is enforced at build time by the compiler. This section defines a simple interface and explains the necessary changes for any class that implements it. void speedUp(int increment){}. What Is an Interface? An interface is a contract between a class and the outside world. an interface is a group of related methods with empty bodies. and you'd use the implements keyword in the class declaration: class ACMEBicycle: public IBicycle { // remainder of this class implemented as before } Implementing an interface allows a class to become more formal about the behavior it promises to provide. However.

(This is Pygame for Python 2. download and install the newer Pygame. If you see a newer version on the website. You do not want to download the "source" for Pygame. In a web browser. sound.6 on Windows. all of our games have only used text. This book assumes you have the Windows operating system.1.) The current version of Pygame at the time this book was written is 1.Game Scripting with Python – Tim Glasser Appendix C . But in this chapter. but included in other programs to add new features. If you installed a different version of Python (such as 2. Text is displayed on the screen as output. we will make some more exciting games with advanced graphics and sound using the Pygame library.1. follow the directions on the download page for installation instructions. but Pygame works the same for every operating system. and other features that games commonly use. You will have to download and install Pygame. but rather the Pygame for your operating system. go to the URL http://pygame.8.org and click on the Downloads link on the left side of the web site. A software library is code that is not meant to be run by itself.5 or 2.Graphics and Animation with Pygame So far. and the player types in text from the keyboard as input.4) download the . You need to download the Pygame installer for your operating system and your version of Python. Pygame is a software library for graphics. 110 . Like Python.msi file.8. By using a library a programmer doesn't have to write the entire program.6. Pygame is available for free.win32-py2. but can make use of the work that another programmer has done before them.msi file for your version of Python. This is simple. download the pygame-1. which is as easy as downloading and installing the Python interpreter. and an easy way to learn programming. For Mac OS X and Linux. For Windows.

font rendering) and sound devices (effects and music). then you know Pygame has successfully been installed. This chapter has five small programs that demonstrate how to use the different features that Pygame provides. then try to install Pygame again (and make sure you typed import pygame correctly). FULLSCREEN) Call set_mode to switch from windowed (the default) to fullscreen mode. 768). other people have done a really excellent job of providing Python libraries for user input and game output.Game Scripting with Python – Tim Glasser On Windows. The key to designing interesting games is to do something different or new. Fortunately. If you are using DOUBLEBUF. image blitting.display. pygame.flip() Drawing an Image 111 . type the following into the interactive shell: >>> import pygame I f nothing appears after you hit the Enter key. keyboard. Creating and Managing the Screen from pygame. PyGame provides user input handling (mouse. Python is possibly the simplest language for writing game simulations in. easy to learn. handles a lot of programming housekeeping and is reasonably fast.display. then you need to flip the screen after you've rendered it. If the error ImportError: No module named pygame appears.set_mode((1024. Games consist largely of user input.locals import * screen = pygame. double click on the downloaded file to install Pygame.set_mode((1024. joystick) and game output via the screen (shape drawing. It's clear to read and write. game output and some sort of world simulation. In the last chapter. Python is a really nice language for writing game simulations in. To check that Pygame is install correctly. 768)) screen = pygame. Other display mode flags (you just | them together): DOUBLEBUF should be used for smooth animation. you will use these features for a complete game written in Python with Pygame.display.

display.load('car. (50. Sprites. 0)) screen.pi / 180) screen. the BLIT (Block Image Transfer). the most common of which are: import pygame pygame.rotate(car. mentioned later. Images can also be rotated: import math car = pygame. (50.poll() pygame.Game Scripting with Python – Tim Glasser To draw an image on screen we use one of the most important drawing primitives. 0. help us do this.load('car. This copies an image from one place (eg. 45 * math.transform. It's usually better to update the parts of the screen that have changed instead. Input handling There are a number of ways to get user events in PyGame. the screen at x = 50.g.image. We always start counting x coordinates from the left.flip() The car should appear on the screen with its top left corner positioned at (50. and y coordinates from the top of the screen.get() 112 . 100). your source image) to another place (e.fill((0.event.image.event.blit(car. 100)) pygame.png') screen.png') rotated = pygame. 0)) Clearing and redrawing a screen is quite a slow technique of animating. 100)) pygame.event.flip() Animating the Image Animating anything on screen involves drawing a scene. y = 100).display.blit(car.wait() pygame. (i. clearing it and drawing it again slightly differently: for i in range(100): screen.blit(car. car = pygame.

Clock() FRAMES_PER_SECOND = 30 deltat = clock. This effectively limits the number of calls to tick to 30 per second. it returns NOEVENT and you can do other things. If there are no events.image. Bringing together some elements The following code will animate our little car according to user controls.load('car.png') clock = pygame.Game Scripting with Python – Tim Glasser Wait will sit and block further game execution until an event comes along. your game will run as fast as it possibly can on whatever platform it happens to be on. 768)) car = pygame.30 times a second is a reasonable number to aim for If a game is action oriented. Timing control is easy to add: clock = pygame. you may wish to aim for double that so that players feel their input is being processed in a super responsive manner. animation and rendering): # INTIALISATION import pygame. The actual time between tick calls is returned (in milliseconds) – on slower computers you might not be achieving 30 ticks per second.) Timing Without timing control. user input. Poll will see whether there are any events waiting for processing. as you animation needs to happen simultaneously. Note that the 30 frames per second will also determine how often your game responds to user input. sys from pygame.Clock() k_up = k_down = k_left = k_right = 0 speed = direction = 0 position = (100. Get. math.tick(FRAMES_PER_SECOND) tick instructs the clock object to pause until 1/30th of a second has passed since the last call to tick.set_mode((1024.locals import * screen = pygame. is like poll except that it returns all of the currently outstanding events (you may also filter the events it returns to be only key presses. It consists broadly of four sections (initialization. or mouse moves. Checking for user input any slower than 30 frames per second will result in noticeable delays for the user.display. as that is checked at the same time that the screen is drawn. This is not generally very useful for games. 100) TURN_SPEED = 5 113 .time.time. etc.

key == K_DOWN: k_down = down elif event. To do this. rect) pygame.transform.get_rect() rect. y) # RENDERING # . A sprite holds an image (e. we can use sprites. a car) and information about where that image should be drawn on screen (i. rotate the car image for direction rotated = pygame.type == KEYDOWN # key down if event. new position based on current position.key == K_ESCAPE: sys. direction) # .g.) This information is stored on the sprite's 114 . position the car on screen rect = rotated.exit(0) screen.event..flip() More structure Most designs will need better control simulation and rendering.key == K_UP: k_up = down * 2 elif event.blit(rotated.0.e.rotate(car.key == K_LEFT: k_left = down elif event.center = position # .. render the car to screen screen.sin(rad) y += speed* math.0) # GAME LOOP while 1: # USER INPUT clock.fill(BLACK) or up? * 5 * 5 * 2 # quit the game # SIMULATION # ..Game Scripting with Python – Tim Glasser ACCELERATION = 2 MAX_FORWARD_SPEED = 10 MAX_REVERSE_SPEED = 5 BLACK = (0.pi / 180 x += speed* math.display.key == K_RIGHT: k_right = down elif event.. new speed and direction based on acceleration and turn speed += (k_up + k_down) if speed > MAX_FORWARD_SPEED: speed = MAX_FORWARD_SPEED if speed < MAX_REVERSE_SPEED: speed = MAX_REVERSE_SPEED direction += (k_right + k_left) # .. speed and direction x.get(): if not hasattr(event. y = position rad = direction * math.cos(rad) position = (x. 'key'): continue down = event. its position.tick(30) for event in pygame.

y = self. self.Clock() class CarSprite(pygame.display.k_down) if self.locals import * screen = pygame. Sprite groups have a draw method which draws the group's sprites onto a supplied surface.position = (x.MAX_FORWARD_SPEED if self.MAX_FORWARD_SPEED: self.sprite.image.rotate(self.k_left = self.get_rect() self.Sprite): MAX_FORWARD_SPEED = 10 MAX_REVERSE_SPEED = 10 ACCELERATION = 2 TURN_SPEED = 5 def __init__(self.rect = self.speed > self.k_up = 0 def update(self. speed*math. They also have a clear method which can remove their sprites from the surface.direction * math.speed = self.set_mode((1024.speed = self.direction) self.cos(rad) self. deltat): # SIMULATION self.direction = 0 self.sin(rad) y += self.position = position self. speed*math.k_up + self. 768)) clock = pygame. sys from pygame.src_image = pygame.speed < self.center = self.load(image) self.src_image.Game Scripting with Python – Tim Glasser image and rectangle(rect) attributes.k_left) x.speed += (self.Sprite.sprite.transform. MAX_REVERSE_SPEED: self.image = pygame. Sprites are always dealt with in groups .time.k_right = self.__init__(self) self. position): pygame.position 115 .position rad = self. MAX_REVERSE_SPEED self. y) self. math.k_down = self.speed = self.pi / 180 x += self.k_right + self. image.image.rect. The above code rewritten using a sprite: # INTIALISATION import pygame.direction += (self.even if a group only has one Sprite.

RenderPlain(car) while 1: # USER INPUT deltat = clock. 'key'): continue down = event. The benefit of sprites really comes when you have a lot of images to draw on screen.tick(30) for event in pygame.image = self.image.update(deltat) car_group.k_down = down * 2 elif event.key == K_UP: car. rect.hit else: self.type == KEYDOWN if event.0)) car_group.load('pad_hit.png') hit = pygame.png') def __init__(self.display. hit_list): if self in hit_list: self.0.exit(0) # RENDERING screen.Game Scripting with Python – Tim Glasser # CREATE A CAR AND RUN rect = screen.draw(screen) pygame.sprite.key == K_RIGHT: car.png'.fill((0.normal pads = [ 116 .k_left = down * 5 elif event.k_right = down * 5 elif event.rect.flip() Mostly the code has just been moved around a little.Sprite): normal = pygame.sprite.key == K_ESCAPE: sys.Rect(self.get(): if not hasattr(event.image. position): self.center = position def update(self.key == K_DOWN: car. Checking for collisions is really pretty easy.k_up = down * 2 elif event.event.center) car_group = pygame.normal.key == K_LEFT: car.rect = pygame.load('pad_normal.get_rect() car = CarSprite('car.get_rect()) self. Let's put some pads to drive over into the simulation: class PadSprite(pygame.image = self. PyGame sprites have additional functionality that help us determine collisions.

center = position self.update(collisions) pad_group.get_rect()) self. 200)). We'll keep information indicating which order the pads must be visited: class PadSprite(pygame.sprite. PadSprite((200. PadSprite(2.spritecollide(car. pad_group) pad_group. just before we draw the car.load('pad_normal.Rect(self.draw(screen) So now we have a car. position): pygame. PadSprite(4. we check to see whether the car sprite is colliding with any of the pads.rect. number.load('pad_hit. PadSprite((800. (800. ] pad_group = pygame. (800.rect = pygame. 200)). 200)). (200. ] current_pad_number = 0 Now we replace the pad collision from above with code that makes sure we hit them in the correct order: pads = pygame. and pass that information to pad.png') def __init__(self. 600)).__init__(self) self.Sprite): normal = pygame. PadSprite(3.number = number self. controlled by the player and we can detect when the car hits other things on the screen. 200)).RenderPlain(*pads) now at the animation point.Sprite.sprite.Game Scripting with Python – Tim Glasser PadSprite((200. False) if pads: pad = pads[0] 117 . running around on the screen.image. 600)). 600)).sprite. (200.png') hit = pygame.spritecollide(car_group. PadSprite((800.normal pads = [ PadSprite(1.image = self.image.sprite. pad_group.update() so each pad knows whether to draw itself “hit” or not: collisions = pygame. Adding objectives It would be great if we could determine whether the car has made a "lap" of the "circuit" we've constructed.normal.sprite. 600)).

118 . and a good rule of thumb is to not optimize unless you really need to.image.number == current_pad_number + 1: pad. background) Now we are only ever updating the small areas of screen that we need to update.png') screen.blit(self.0)) Now inside the loop. but before we update and move the car. This is quite slow (though you might not notice) and is easily improved upon.blit(self.hit current_pad_number += 1 elif current_pad_number == 4: for pad in pad_group.background.clear(screen. (0.png') screen.Game Scripting with Python – Tim Glasser if pad. resetting the current_pad_number is where we'd flag that the player has run a lap.load('track. A further optimization would be to recognize that the pads only get updated very infrequently. and not draw / clear them each frame unless their state actually changes. We do this with the pads too: background = pygame.clear(screen.image = pad. background) car_group.fill((0. it just unnecessarily complicates your code. (0.background.0))).0. This optimization is not necessary just yet. we ask the car's sprite to clear itself from the screen.sprites(): pad.0)) pad_group.load('track. Adding a background Currently we are clearing the screen on every frame before rendering (screen.image = pad. Firstly outside the animation loop we load up a background image and draw it to the screen: background = pygame.normal current_pad_number = 0 The last part of that text.image.

Sign up to vote on this title
UsefulNot useful