magic 8 ball putting it all together
TRANSCRIPT
3-3: Project
Objectives: Learn how to handle input
Learn how to define a function
Put together a program that acts as a “magic 8-ball”
Set up the Pi kits as normal. Start the X Windows System and open IDLE.
It can be useful to interact with a user. We have seen how to create output, but
what about handling input from the keyboard?
There are two related ways to do this. The first is the input function, which handles
numbers well:
>>> input("Number -->") Number -->12
12
>>>
Notice how Python print s whatever you tell the input function to use, and waits for
you to type something and press enter. If you enter anything other than a number, you will get some kind of error. [Exception: it is possible to enter valid Python code
that evaluates to a number. For example, if you type len(“hello”) at the prompt, it will be accepted and return the number 5.]
That's great, but what if you want to hold on to what the user entered? Use the input() function as part of a variable assignment.
>>> x = input("What is x? ")
What is x? 42
>>> x 42
>>>
Being limited to numbers only is pretty restrictive. If you want to accept anything the user enters, you can use the raw_input function instead.
>>> x = raw_input("What is x? ") What is x? The quick brown fox jumped over the lazy dogs.
>>> x
'The quick brown fox jumped over the lazy dogs.' >>>
Notice, however, that if you provide a number to raw_input, it is st ill interpreted as a
string, so you cannot directly perform operations like “x + 1” meaningfully.
Functions: We have seen several cases where we ask something like len() or sort() or input() to
do a task for us, repeatedly. We can define our own such tasks, and they are called
functions. In a basic sense, they have a name, they may accept some input, and they may return a value. The easiest way to define a function is with the def keyword,
and we use the return keyword to indicate what comes back.
>>> def plus(a, b):
return a + b
As usual, when we put the colon on the end of the first line, we're saying “I 'm not
done” and the subsequent lines are consistent ly indented. Python allows us to do just about anything we like within a function definit ion, including calling (or even
creating) other functions. Now we can call our function just like any ot her:
>>> plus(3, 2)
5 >>>
There are lots of functions that are already defined for us, but sometimes we have to tell Python where to find them. There is a random number generator, for example,
that we can use if we ask Python to load it :
>>> import random
The random() function gives us a decimal number between 0 and 1:
>>> random.random()
0.09922611904874357
>>> random.random() 0.5130440719955642
>>> random.random()
0.2534538950733807 >>> random.random()
0.8071376093891092
More frequently, however, we will use random numbers that are integers – consider a
die roll (1d6), for example. The function randint(min, max) helps us with that. >>> random.randint(1, 6)
5
>>> random.randint(1, 6) 4
>>> random.randint(1, 6) 3
>>> random.randint(1, 6) 6
>>> random.randint(1, 6) 3
>>> random.randint(1, 6)
1 >>>
Now we have all the tools we need to solve some real-world problems. How about creating a program that acts as a “Magic 8-ball” for us? Ask a quest ion, shake the
Magic 8-ball, and it reveals to us an answer.
First , we need some answers that it can give us. Define them as a list called
“answers.”
>>> answers = ['Yes', 'No', 'Maybe', 'Ask again', '73% chance', 'Orange', "Batman", 42]
Now we need a way to pick one of the answers, randomly. We will do this
repeatedly, so define a function to do this. The input will be the answer list , and the output will be one of the answers. We will choose a random number between 0 and
the highest index of a list item, which is len(list) – 1. Notice that the name of what we
use in the function does not have to match any exist ing variable name, and might well be clearer if it purposely doesn't .
>>> def pickAnAnswer(answerList):
highest = len(answerList) - 1
index = random.randint(0, highest) return answerList[index]
We also need a way to reveal the answer, which some appropriate print statements.
Optionally, you can make the program appear to be thinking for some period of t ime
(perhaps for dramatic tension?), and if you choose to do so, be sure to load the t ime-related functions.
>>> import t ime >>> def delay(howLong):
for x in range(0, howLong): print('...thinking...')
t ime.sleep(1)
>>> def revealAnswer(question, answer, thinkingTime):
print('Considering your quest ion: ' + quest ion)
delay(thinkingTime) print('The Magic 8-ball has spoken! The answer you seek is this:')
print(answer)
Next, we need a way to allow the user to ask a quest ion. We want to be able to do this over and over again, so another function is in order. This one will be simple.
>>> def askAQuest ion(prompt):
return raw_input(prompt + ' --> ')
We have all the components in place. Now we need a loop that will allow us to keep
asking as many quest ions as we like, or a certain number of quest ions. We also need
to make sure that we init ialize the quest ion to something, so the program knows it exists.
>>> quest ion = 'none yet '
>>> while (quest ion != 'exit '):
quest ion = askAQuest ion("What is your quest ion? ") if quest ion != "exit ":
answer = pickAnAnswer(answers) revealAnswer(question, answer, 1)
What is your quest ion? --> Should I exit?
Considering your quest ion: Should I exit?
...thinking... The Magic 8-ball has spoken! The answer you seek is this:
Ask again What is your quest ion? --> Should I exit?
Considering your quest ion: Should I exit?
...thinking... The Magic 8-ball has spoken! The answer you seek is this:
Maybe What is your quest ion? --> How about now?
Considering your quest ion: How about now?
...thinking... The Magic 8-ball has spoken! The answer you seek is this:
Orange
What is your quest ion? --> Um, should I exit now? Considering your quest ion: Um, should I exit now?
...thinking... The Magic 8-ball has spoken! The answer you seek is this:
73% chance
What is your quest ion? --> Okay, how about now? Considering your quest ion: Okay, how about now?
...thinking...
The Magic 8-ball has spoken! The answer you seek is this: Yes
What is your quest ion? --> exit >>>
Here is the complete text of the program.
import random
import t ime
answers = ['Yes', 'No', 'Maybe', 'Ask again', '73% chance', 'Orange', “Batman”, 42]
def askAQuest ion(prompt):
return raw_input(prompt + ' --> ')
def pickAnAnswer(answerList): highest = len(answerList) - 1
index = random.randint(0, highest)
return answerList[index]
def delay(howLong):
for x in range(0, howLong): print('...thinking...')
t ime.sleep(1)
def revealAnswer(question, answer, thinkingTime):
print('Considering your quest ion: ' + quest ion) delay(thinkingTime)
print('The Magic 8-ball has spoken! The answer you seek is this:')
print(answer)
quest ion = 'none yet ' while (quest ion != 'exit '):
quest ion = askAQuest ion("What is your quest ion? ") if quest ion != “exit”:
answer = pickAnAnswer(answers) revealAnswer(question, answer, 1)
The answers list can be customized, of course, and can also be modified between runs of the program. Have some fun with it !
Pack up the kits, and revel in the knowledge that you have begun to take full control of a Raspberry Pi.