Raspberry Pi A User Manual page 199

Hide thumbs Also See for Raspberry Pi A:
Table of Contents

Advertisement

C H A P T E R 1 2
when it prints integers and strings together. Finally, note that there is no division operation
(which would be indicated with the / symbol). This is because the example calculator program
uses integers, which can only be whole numbers, with no decimal places or fractions allowed.
Although the calculation part of the program is now complete, it will run forever because
there is currently nothing to tell Python when it's time to exit the loop. To provide the user
with a way to exit the program, add the following line:
goAgain = int(raw_input("Type 1 to enter more numbers, ↵
or any other number to quit: "))
This allows the user to change the
user enters the number
However, if the user enters any other number, the evaluation is no longer true (
no longer equal to
), and the loop will end.
1
The finished program should look like this, remembering that anything marked with
should be entered onto a single line:
#!/usr/bin/env python
# Example 2: A Python program from the Raspberry Pi User Guide
userName = raw_input("What is your name?
print "Welcome to the program,", userName
goAgain = 1
while goAgain == 1:
firstNumber = int(raw_input("Type the first number: "))
secondNumber = int(raw_input("Type the second number: "))
print firstNumber, "added to", secondNumber, "equals", ↵
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
menu in IDLE or by typing
when prompted, and then provide the numbers that you want to calculate (see Figure 12-5)
until you get bored and then type anything other than 1 to exit the program.
A N I N T R O D U C T I O N T O P Y T H O N
variable, which controls the
goAgain
, the
variable is still equal to
1
goAgain
, and run it by choosing Run Module from the Run
python calculator.py
while
and the loop will run again.
1
")
at the terminal. Enter your user name
loop. If the
is
goAgain
183

Hide quick links:

Advertisement

Table of Contents
loading

Related Products for Raspberry Pi Raspberry Pi A

This manual is also suitable for:

Raspberry pi b

Table of Contents