Python Programs For Beginners

This is an introduction to fundamental PythonLanguage syntax and programming. It is modeled after the CeeProgramsForBeginners page.

So far, all the programs run with MacPython version 2.3 on MacOs 9. They should be suitable with any variety of Python. There's nothing avant-garde in any of the code... yet.

Like CeeLanguage, CeePlusPlus, JavaLanguage, and JavaScript, Python is one of those languages whose syntax is in the AlgolFamily. So if you are familiar with any of these other languages, you will be able to read and follow a Python program pretty easily.


Program # 1: Hello world. (How to start and end a program. How to write something to line output.)

There are several different ways to create and run a program in Python. You could go the traditional programming route by writing your code in a text file with your favorite text editor. Then you would call the Python Interpreter to run your program file. Or you could launch the Python IDE, type the code into a text file using the IDE's editor, then run it via the IDE.

If you're just experimenting or writing tiny throw-away code, you don't need to write and save your code to a file! You can type each line of the code in the IDE's Interactive window, and watch each line get executed after you hit the return key. Or you can launch the Python Interpreter, type each line there, and watch each line get executed.

Launch the Python Interpreter or launch the Interactive window in the Python IDE. Type

 print 'Hello, world!'
and hit return. You may use either single or double quotes, as long as the quotes match, that is. Notice that the interpreter executes that little line of code you just wrote and displays its result. Man, was that easy!

Save this in a text file with extension .py (like, hello.py):

 print 'Hello, world!'
If your OS has a command line window, just enter this on the command line:

 python hello.py
Or if your OS associates the .py extension with the Python Interpreter, just double click the hello.py icon. (On a pre-MacOsx Mac, you need to set the file's creator code to Pyth to run it in the Python Interpreter or Pide to run it in the Python IDE.)

Try this in your Python Interpreter:

 'Hello, world!'
Notice that the interpreter takes a look at that little expression you just wrote and displays its result. Notice that it displays the text string with the quotes. Whenever you type into the interpreter anything that has no syntax problems, whether it be a full-blown execution statement or even just an expression like the name of a variable that already has something stored in it, the interpreter displays what's known as a "representation" of the statement result or expression.

Try this in your .py file:

 'Hello, world!'
Notice that when you run this new program without the print statement, nothing shows up. The Python Interpreter evaluated the expression, all right, but because the interpreter considers your program file to be the "main" routine and you didn't tell the interpreter to output anything, you got no output. When there's no print statement, there's no output unless the Python Interpreter or IDE is "main" routine.


Program # 2: A number is asked from the user, some math is performed, and the result is displayed. (Prompting for input. Storing a value in a variable. Converting strings and integers. Using C-style formatting.)

Type what you see here after each triple bracket (the Python Interpreter prompt). The lines that don't begin with triple angles are the interpreter's response.

 >>> age = raw_input('Hey, dude, how old might you be? ')
 Hey, dude, how old might you be? 43
Here we've called a function, raw_input, to get some input from the user. The argument to the function is a string that gets displayed as a prompt. We've assigned the user's response to the variable age.

Unlike many other languages, PythonLanguage uses what's known as DynamicTyping. Therefore, there's no such thing as "declaring" the variable's "type" because Python variables don't even have type. The data the variable contains (points to?) has a particular type, but the variable does not. So, just invent a name for your variable and start using it. A valid name can contain lower-case letters, upper-case letters, numerals, and underscores, but it cannot begin with a numeral. Python is case-sensitive, so keep in mind that Age would not be the same variable as age.

 >>> age
 '43'
When working in the interpreter, you can enter the name the variable to see the value stored in it. Notice that the interpreter displays the value of age surrounded by quotes. This means that age contains a string, not a number. Whenever you're not sure how to use a function, just try it in the interpreter and examine its result. Here you've just discovered that the raw_input function returns a string. That's good to know.

 >>> print 'Dude, you are', age, 'years old but you look like', age+10
 TypeError: cannot concatenate 'str' and 'int' objects
Oh oh. You want to add 10 to the person's age, but Python can't add a number to a string. Because string age came first in final the expression, Python complains that it can't concatenate a number to the string.

 >>> print 'Dude, you are', age, 'years old but you look like', int(age)+10
 Dude, you are 43 years old but you look like 53
That's better. But it would be nice to stick some punctuation at the end of the sentence, say an exclamation point. Notice that when separating print statement items with a comma, that Python automatically outputs a space between each item. That's really convenient, but we don't want a space before the exclamation point. We could concatenate the punctuation to the end of the output, but that means we first have to turn the number calculation into a string.

 >>> print 'Dude, you are', age, 'years old but you look like', str(int(age)+10) + '!'
 Dude, you are 43 years old but you look like 53!
Well, that worked but it's pretty awkward. Converting a string to a number, converting a number to a string, "adding" an exclamation point to the end of the string. Eeks. So let's use good ol' C-style formatting.

 >>> print 'Dude, you are %s years old but you look like %d!' % (age, int(age)+10)
 Dude, you are 43 years old but you look like 53!
Now you're cookin'! Here, %s in the format string means "fill me in with a string." and %d means "fill me in with an integer." The percent sign after the format string is known as the formatting or interpolation operator. What comes next is a tuple containing the items that are to be filled into the format string. The items must be in the same order they should be inserted into the format string.

 age = raw_input('Hey, dude, how old might you be? ')
 age = int(age)
 print 'Dude, you are %d years old but you look like %d!' % (age, age+10)
So that doing potentially lots of math with the person's age will be easier, we've converted the value of age to an integer and reassigned that value to the variable. This, of course, means that we have to use the %d format code for age.


Program # 3: The user is asked to input his full name, and the program greets him by first name and remarks about the last name. (Splitting a string. Accessing items from a list. Asking Python for help.)

 >>> fullname = raw_input('What is your full name? ')
 What is your full name? Marie Sklodowska Curie
 >>> fullname
 'Marie Sklodowska Curie'
No surprises there. But if you're coming from a knowledge of other languages, you might be pleasantly amazed that raw_input returns everything the user typed (not counting the return) as one whole string. It does not look at the space between the names and retrieve the input as several strings.

A string, actually a str, has several methods or functions that can be called. Calling the help function with str as its argument lists these methods, their arguments, what they do, and what sort of output they return. (Your Python IDE might show you the list of methods without your using the help function.)

 >>> help(str)
 Help on class str in module __builtin__:
 etc., etc., etc.
 |  split(...)
 |      S.split([sep [,maxsplit]]) -> list of strings
 |      
 |      Return a list of the words in the string S, using sep as the
 |      delimiter string.  If maxsplit is given, at most maxsplit
 |      splits are done. If sep is not specified or is None, any
 |      whitespace string is a separator.
 etc., etc., etc.

>>> namelist = fullname.split() >>> namelist ['Marie', 'Sklodowska', 'Curie']
Here we see a list of three strings. Python doesn't have arrays. Its collection workhorse is the list. A list is like a conventional array, but each item in the list can be a different size or even a different type. And so it's kind of like a JavaScript array. You might want to take a look at help(list).

Items from a Python list are retrieved by index number, just as they would be from a C/C++ array. The numbering always begins at 0. In fact, unlike a JavaScript array, a Python list is never "associative"; the indices are always integers starting at 0 without gaps between the numbers. (If you want Python's equivalent of an associative array, you want a dictionary or dict.)

We have a list of three strings. Let's examine it a bit.

 >>> len(namelist)
 3
 >>> namelist[0]
 'Marie'
 >>> namelist[1]
 'Sklodowska'
 >>> namelist[2]
 'Curie'
 >>> namelist[-1]
 'Curie'
 >>> namelist[-2]
 'Sklodowska'
We can determine how many items are in the list by using the len function. As in many other languages, we access an item in the list by placing the index of interest within square brackets. Here's a nifty feature of Python: the last item in a list can be accessed by using -1 as the index, the second to last item can be accessed by using -2 as the index, etc.

 >>> print "%s, you're the only person I know named %s." % (namelist[0], namelist[-1])
 Marie, you're the only person I know named Curie.
Notice that we used double quotes around this format string instead of single quotes so that Python will know that the single quote (apostrophe) after you does not mark the end of the string.

Another example of string splitting and list indexing in action:

 >>> fullname = 'Madonna'
 >>> namelist = fullname.split()
 >>> namelist
 ['Madonna']
 >>> print namelist[0], namelist[-1]
 Madonna Madonna
 fullname = raw_input('What is your full name? ')
 namelist = fullname.split()
 print "%s, you're the only person I know named %s." % (namelist[0], namelist[-1])


Program # 4: A text adventure game based on game in CeeProgramsForBeginners.

 class Map:
     def __init__(self, message, first, second):
         self.message = message
         self.first_choice = first
         self.second_choice = second

END = 20 locations = [ Map("You are on a footpath. To go to the forest enter 1, to go to the stream enter 2: ", 1, 4), Map("You are in the forest. Enter 1 to go to the clearing or 2 to return to the footpath: ", 2, 0), Map("You are in the clearing. Enter 1 to go to the fairy circle or 2 to return to the forest: ", 3, 1), Map("You are in the fairy circle. Enter 1 to leave the world or 2 to return to the clearing: ", 8, 2), Map("You are standing next to a stream. Enter 2 to find a bridge or 1 to go back to the footpath: ", 0, 5), Map("You have found a bridge. To cross the bridge to the fort enter 2, or enter 1 to go back to the stream: ", 4, 6), Map("You have reached the fort. Enter 2 to go to bed or 1 to go back to the bridge: ", 5, 7), Map("Night-night, sleepy head. Thank you for playing.", END, END), Map("Thanks for playing. I hope you enjoyed exploring. See you soon.", END, END) ]

if __name__ == '__main__': current_index = 0 while current_index != END: current_location = locations[current_index] try: user_choice = int(raw_input(current_location.message)) except: user_choice = 1 if user_choice == 1: current_index = current_location.first_choice else: current_index = current_location.second_choice


Program # 5: Text adventure game based on game in CppLearningDiscussion.

 class RoomDefinition:
     def __init__(self, description='You are here.', nextRooms=(None,None)):
         self.description = description
         self.nextRooms = nextRooms # tuple of RoomDefinitions
     def setInfo(self, description, *rooms):
         # all rooms arguments automatically collected into tuple
         self.description = description
         if rooms: self.nextRooms = rooms

footpath = RoomDefinition() forest = RoomDefinition() clearing = RoomDefinition() fairycircle = RoomDefinition() stream1 = RoomDefinition() bridge = RoomDefinition() fort = RoomDefinition() bed = RoomDefinition( "Night-night, sleepy head. Thank you for playing.") finishgame = RoomDefinition( "Thanks for playing. I hope you enjoyed exploring. See you soon.")

footpath.setInfo( "You are on a footpath. To go to the forest enter 1, to go to the stream enter 2: ", forest, stream1) forest.setInfo( "You are in the forest. Enter 1 to go to the clearing or 2 to return to the footpath: ", clearing, footpath) clearing.setInfo( "You are in the clearing. Enter 1 to go to the fairy circle or 2 to return to the forest: ", fairycircle, forest) fairycircle.setInfo( "You are in the fairy circle. Enter 1 to leave the world or 2 to return to the clearing: ", finishgame, clearing) stream1.setInfo( "You are standing next to a stream. Enter 2 to find a bridge or 1 to go back to the footpath: ", footpath, bridge) bridge.setInfo( "You have found a bridge. To cross the bridge to the fort enter 2, or enter 1 to go back to the stream: ", stream1, fort) fort.setInfo( "You have reached the fort. Enter 2 to go to bed or 1 to go back to the bridge: ", bridge, bed)

def moveSomewhere(currentRoom): try: userChoice = int(raw_input()) except: userChoice = 1 return currentRoom.nextRooms[userChoice-1]

if __name__ == '__main__': room = footpath while room: print room.description, room = moveSomewhere(room)


Contributors: ElizabethWiethoff, JonathanTang for game logic


CategoryPython CategoryExample CategoryInManyProgrammingLanguages


EditText of this page (last edited June 30, 2004) or FindPage with title or text search