Hardware Reference
In-Depth Information
print firstNumber, “multiplied by”, secondNumber, “equals”, Æ
firstNumber * secondNumber
Notice that while the addition and subtraction operations use the expected plus and minus
symbols, multiplication uses the * symbol. Also notice that there are no formatting spaces
between the quotation marks. his is because Python automatically adds spaces where required
when it prints integers and strings together. Finally, note that there is no division operation
(which would be indicated with the / symbol). his 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: “))
his allows the user to change the goAgain variable, which controls the while loop. If the
user enters the number 1 , the goAgain variable is still equal to 1 and the loop will run again.
However, if the user enters any other number, the evaluation is no longer true ( goAgain is
no longer equal to 1 ), and the loop will end.
he inished 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: “))
Search WWH ::




Custom Search