Operation Manual
firstNumber + secondNumber
print firstNumber, “minus”, secondNumber, “equals”,
firstNumber - secondNumber
print firstNumber, “multiplied by”, secondNumber, “equals”,
firstNumber * secondNumber
goAgain = int(raw_input(“Type 1 to enter more numbers, or
any other number to quit: “))
Save the program as calculator.py, and run it by choosing Run Module from the Run menu in IDLE or by typing python
calculator.py at the terminal. Enter your user name when prompted, and then provide the numbers that you want to calculate
(see Figure 11-5) until you get bored and type anything other than 1 to exit the program.
Figure 11-5: Running calculator.py in IDLE
For more short programs that introduce important Python concepts, visit the official Python Simple Programs wiki page at
http://wiki.python.org/moin/SimplePrograms.
Example 3: Gaming with pygame
To illustrate the power of Python, this example creates a fully-functional arcade game based on the classic game of Snake or
Nibbles. To accomplish this, it uses an external Python library called pygame.
Originally written by Pete Shinners, pygame is a collection of python modules designed to add new functionality to the language
—functionality specifically designed to make it easy to write a game in Python. Each pygame module provides a function
required by a modern game, including sound, graphics and even networking support. Although it’s possible to write a game in
Python without using pygame, it’s a lot easier if you take advantage of the code already written in the pygame library.
Before you can write a pygame program, you need to install the pygame library. If you’re using the recommended Debian
distribution, this is as simple as typing the following at the console or terminal:
sudo apt-get install python-pygame
For other distributions, the pygame source files can be downloaded from the official pygame website at
http://www.pygame.org/download.shtml. Instructions for installation are provided on the same page.
Starting a pygame program is the same as starting any other Python project. Open a new blank document in either IDLE or a
text editor, and add the following shebang line to the top:
#!/usr/bin/env python
Next you need to tell Python that this program uses the pygame modules. To do this, you use an import instruction, which tells
Python to load an external module (another Python file) and make it accessible from the current program. Type the following two
lines to import the necessary modules into your new project: