SlideShare a Scribd company logo
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 prints 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 still 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 consistently indented. Python allows us to do just
about anything we like within a function definition, 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 question, 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 existing 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 time
(perhaps for dramatic tension?), and if you choose to do so, be sure to load the time-
related functions.
>>> import time
>>> def delay(howLong):
for x in range(0, howLong):
print('...thinking...')
time.sleep(1)
>>> def revealAnswer(question, answer, thinkingTime):
print('Considering your question: ' + question)
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 question. We want to be able to do
this over and over again, so another function is in order. This one will be simple.
>>> def askAQuestion(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 questions as we like, or a certain number of questions. We also need
to make sure that we initialize the question to something, so the program knows it
exists.
>>> question = 'none yet'
>>> while (question != 'exit'):
question = askAQuestion("What is your question? ")
if question != "exit":
answer = pickAnAnswer(answers)
revealAnswer(question, answer, 1)
What is your question? --> Should I exit?
Considering your question: Should I exit?
...thinking...
The Magic 8-ball has spoken! The answer you seek is this:
Ask again
What is your question? --> Should I exit?
Considering your question: Should I exit?
...thinking...
The Magic 8-ball has spoken! The answer you seek is this:
Maybe
What is your question? --> How about now?
Considering your question: How about now?
...thinking...
The Magic 8-ball has spoken! The answer you seek is this:
Orange
What is your question? --> Um, should I exit now?
Considering your question: Um, should I exit now?
...thinking...
The Magic 8-ball has spoken! The answer you seek is this:
73% chance
What is your question? --> Okay, how about now?
Considering your question: Okay, how about now?
...thinking...
The Magic 8-ball has spoken! The answer you seek is this:
Yes
What is your question? --> exit
>>>
Here is the complete text of the program.
import random
import time
answers = ['Yes', 'No', 'Maybe', 'Ask again', '73% chance', 'Orange', “Batman”, 42]
def askAQuestion(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...')
time.sleep(1)
def revealAnswer(question, answer, thinkingTime):
print('Considering your question: ' + question)
delay(thinkingTime)
print('The Magic 8-ball has spoken! The answer you seek is this:')
print(answer)
question = 'none yet'
while (question != 'exit'):
question = askAQuestion("What is your question? ")
if question != “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.

More Related Content

What's hot

Python
PythonPython
java 8 Hands on Workshop
java 8 Hands on Workshopjava 8 Hands on Workshop
java 8 Hands on Workshop
Jeanne Boyarsky
 
Practice
PracticePractice
Practice
Daman Toor
 
Begin with Python
Begin with PythonBegin with Python
Begin with Python
Narong Intiruk
 
Analysis of Fatal Utah Avalanches with Python. From Scraping, Analysis, to In...
Analysis of Fatal Utah Avalanches with Python. From Scraping, Analysis, to In...Analysis of Fatal Utah Avalanches with Python. From Scraping, Analysis, to In...
Analysis of Fatal Utah Avalanches with Python. From Scraping, Analysis, to In...
Matt Harrison
 
Python basics
Python basicsPython basics
Learn 90% of Python in 90 Minutes
Learn 90% of Python in 90 MinutesLearn 90% of Python in 90 Minutes
Learn 90% of Python in 90 Minutes
Matt Harrison
 
How to Become a Tree Hugger: Random Forests and Predictive Modeling for Devel...
How to Become a Tree Hugger: Random Forests and Predictive Modeling for Devel...How to Become a Tree Hugger: Random Forests and Predictive Modeling for Devel...
How to Become a Tree Hugger: Random Forests and Predictive Modeling for Devel...
Matt Harrison
 
CPAP.com Introduction to Coding: Part 1
CPAP.com Introduction to Coding: Part 1CPAP.com Introduction to Coding: Part 1
CPAP.com Introduction to Coding: Part 1
johnnygoodman
 
FUNCTIONS IN PYTHON, CLASS 12 COMPUTER SCIENCE
FUNCTIONS IN PYTHON, CLASS 12 COMPUTER SCIENCEFUNCTIONS IN PYTHON, CLASS 12 COMPUTER SCIENCE
FUNCTIONS IN PYTHON, CLASS 12 COMPUTER SCIENCE
Venugopalavarma Raja
 
Introduction to Python and TensorFlow
Introduction to Python and TensorFlowIntroduction to Python and TensorFlow
Introduction to Python and TensorFlow
Bayu Aldi Yansyah
 
Java Foundations: Strings and Text Processing
Java Foundations: Strings and Text ProcessingJava Foundations: Strings and Text Processing
Java Foundations: Strings and Text Processing
Svetlin Nakov
 
Python Modules and Libraries
Python Modules and LibrariesPython Modules and Libraries
Python Modules and Libraries
Venugopalavarma Raja
 
Functions in python
Functions in pythonFunctions in python
Functions in python
Ilian Iliev
 
AmI 2016 - Python basics
AmI 2016 - Python basicsAmI 2016 - Python basics
AmI 2016 - Python basics
Luigi De Russis
 
Python tutorialfeb152012
Python tutorialfeb152012Python tutorialfeb152012
Python tutorialfeb152012
Shani729
 
Python quickstart for programmers: Python Kung Fu
Python quickstart for programmers: Python Kung FuPython quickstart for programmers: Python Kung Fu
Python quickstart for programmers: Python Kung Fu
climatewarrior
 
Python language data types
Python language data typesPython language data types
Python language data types
Hoang Nguyen
 
Python PCEP How To Talk To Computer
Python PCEP How To Talk To ComputerPython PCEP How To Talk To Computer
Python PCEP How To Talk To Computer
IHTMINSTITUTE
 
Python tutorial
Python tutorialPython tutorial
Python tutorial
Rajiv Risi
 

What's hot (20)

Python
PythonPython
Python
 
java 8 Hands on Workshop
java 8 Hands on Workshopjava 8 Hands on Workshop
java 8 Hands on Workshop
 
Practice
PracticePractice
Practice
 
Begin with Python
Begin with PythonBegin with Python
Begin with Python
 
Analysis of Fatal Utah Avalanches with Python. From Scraping, Analysis, to In...
Analysis of Fatal Utah Avalanches with Python. From Scraping, Analysis, to In...Analysis of Fatal Utah Avalanches with Python. From Scraping, Analysis, to In...
Analysis of Fatal Utah Avalanches with Python. From Scraping, Analysis, to In...
 
Python basics
Python basicsPython basics
Python basics
 
Learn 90% of Python in 90 Minutes
Learn 90% of Python in 90 MinutesLearn 90% of Python in 90 Minutes
Learn 90% of Python in 90 Minutes
 
How to Become a Tree Hugger: Random Forests and Predictive Modeling for Devel...
How to Become a Tree Hugger: Random Forests and Predictive Modeling for Devel...How to Become a Tree Hugger: Random Forests and Predictive Modeling for Devel...
How to Become a Tree Hugger: Random Forests and Predictive Modeling for Devel...
 
CPAP.com Introduction to Coding: Part 1
CPAP.com Introduction to Coding: Part 1CPAP.com Introduction to Coding: Part 1
CPAP.com Introduction to Coding: Part 1
 
FUNCTIONS IN PYTHON, CLASS 12 COMPUTER SCIENCE
FUNCTIONS IN PYTHON, CLASS 12 COMPUTER SCIENCEFUNCTIONS IN PYTHON, CLASS 12 COMPUTER SCIENCE
FUNCTIONS IN PYTHON, CLASS 12 COMPUTER SCIENCE
 
Introduction to Python and TensorFlow
Introduction to Python and TensorFlowIntroduction to Python and TensorFlow
Introduction to Python and TensorFlow
 
Java Foundations: Strings and Text Processing
Java Foundations: Strings and Text ProcessingJava Foundations: Strings and Text Processing
Java Foundations: Strings and Text Processing
 
Python Modules and Libraries
Python Modules and LibrariesPython Modules and Libraries
Python Modules and Libraries
 
Functions in python
Functions in pythonFunctions in python
Functions in python
 
AmI 2016 - Python basics
AmI 2016 - Python basicsAmI 2016 - Python basics
AmI 2016 - Python basics
 
Python tutorialfeb152012
Python tutorialfeb152012Python tutorialfeb152012
Python tutorialfeb152012
 
Python quickstart for programmers: Python Kung Fu
Python quickstart for programmers: Python Kung FuPython quickstart for programmers: Python Kung Fu
Python quickstart for programmers: Python Kung Fu
 
Python language data types
Python language data typesPython language data types
Python language data types
 
Python PCEP How To Talk To Computer
Python PCEP How To Talk To ComputerPython PCEP How To Talk To Computer
Python PCEP How To Talk To Computer
 
Python tutorial
Python tutorialPython tutorial
Python tutorial
 

Similar to Magic 8 ball putting it all together

Programming python quick intro for schools
Programming python quick intro for schoolsProgramming python quick intro for schools
Programming python quick intro for schools
Dan Bowen
 
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...
DRVaibhavmeshram1
 
Python 101: Python for Absolute Beginners (PyTexas 2014)
Python 101: Python for Absolute Beginners (PyTexas 2014)Python 101: Python for Absolute Beginners (PyTexas 2014)
Python 101: Python for Absolute Beginners (PyTexas 2014)
Paige Bailey
 
C++ Course - Lesson 2
C++ Course - Lesson 2C++ Course - Lesson 2
C++ Course - Lesson 2
Mohamed Ahmed
 
Introduction to java Programming
Introduction to java ProgrammingIntroduction to java Programming
Introduction to java Programming
Ahmed Ayman
 
Function in Python [Autosaved].ppt
Function in Python [Autosaved].pptFunction in Python [Autosaved].ppt
Function in Python [Autosaved].ppt
GaganvirKaur
 
Python Lecture 4
Python Lecture 4Python Lecture 4
Python Lecture 4
Inzamam Baig
 
Programming with python
Programming with pythonProgramming with python
Programming with python
sarogarage
 
Cc code cards
Cc code cardsCc code cards
Cc code cards
ysolanki78
 
Pythonlearn-03-Conditional.pptx
Pythonlearn-03-Conditional.pptxPythonlearn-03-Conditional.pptx
Pythonlearn-03-Conditional.pptx
VigneshChaturvedi1
 
Input Statement.ppt
Input Statement.pptInput Statement.ppt
Input Statement.ppt
MuhammadJaved672061
 
Introduction to python programming
Introduction to python programmingIntroduction to python programming
Introduction to python programming
Rakotoarison Louis Frederick
 
JavaScript 101
JavaScript 101JavaScript 101
JavaScript 101
Mindy McAdams
 
Python Learn Function with example programs
Python Learn Function with example programsPython Learn Function with example programs
Python Learn Function with example programs
GeethaPanneer
 
Python.pptx
Python.pptxPython.pptx
Lecture-2-Python-Basic-Elements-Sep04-2018.pptx
Lecture-2-Python-Basic-Elements-Sep04-2018.pptxLecture-2-Python-Basic-Elements-Sep04-2018.pptx
Lecture-2-Python-Basic-Elements-Sep04-2018.pptx
AbdulQadeerBilal
 
Notes5
Notes5Notes5
Notes5
hccit
 
Python basics
Python basicsPython basics
Python basics
Himanshu Awasthi
 
Pythonlearn-04-Functions (1).pptx
Pythonlearn-04-Functions (1).pptxPythonlearn-04-Functions (1).pptx
Pythonlearn-04-Functions (1).pptx
leavatin
 
R Debugging
R DebuggingR Debugging
R Debugging
Nilesh Borade
 

Similar to Magic 8 ball putting it all together (20)

Programming python quick intro for schools
Programming python quick intro for schoolsProgramming python quick intro for schools
Programming python quick intro for schools
 
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...
 
Python 101: Python for Absolute Beginners (PyTexas 2014)
Python 101: Python for Absolute Beginners (PyTexas 2014)Python 101: Python for Absolute Beginners (PyTexas 2014)
Python 101: Python for Absolute Beginners (PyTexas 2014)
 
C++ Course - Lesson 2
C++ Course - Lesson 2C++ Course - Lesson 2
C++ Course - Lesson 2
 
Introduction to java Programming
Introduction to java ProgrammingIntroduction to java Programming
Introduction to java Programming
 
Function in Python [Autosaved].ppt
Function in Python [Autosaved].pptFunction in Python [Autosaved].ppt
Function in Python [Autosaved].ppt
 
Python Lecture 4
Python Lecture 4Python Lecture 4
Python Lecture 4
 
Programming with python
Programming with pythonProgramming with python
Programming with python
 
Cc code cards
Cc code cardsCc code cards
Cc code cards
 
Pythonlearn-03-Conditional.pptx
Pythonlearn-03-Conditional.pptxPythonlearn-03-Conditional.pptx
Pythonlearn-03-Conditional.pptx
 
Input Statement.ppt
Input Statement.pptInput Statement.ppt
Input Statement.ppt
 
Introduction to python programming
Introduction to python programmingIntroduction to python programming
Introduction to python programming
 
JavaScript 101
JavaScript 101JavaScript 101
JavaScript 101
 
Python Learn Function with example programs
Python Learn Function with example programsPython Learn Function with example programs
Python Learn Function with example programs
 
Python.pptx
Python.pptxPython.pptx
Python.pptx
 
Lecture-2-Python-Basic-Elements-Sep04-2018.pptx
Lecture-2-Python-Basic-Elements-Sep04-2018.pptxLecture-2-Python-Basic-Elements-Sep04-2018.pptx
Lecture-2-Python-Basic-Elements-Sep04-2018.pptx
 
Notes5
Notes5Notes5
Notes5
 
Python basics
Python basicsPython basics
Python basics
 
Pythonlearn-04-Functions (1).pptx
Pythonlearn-04-Functions (1).pptxPythonlearn-04-Functions (1).pptx
Pythonlearn-04-Functions (1).pptx
 
R Debugging
R DebuggingR Debugging
R Debugging
 

More from geekinlibrariansclothing

Shine a little LED
Shine a little LEDShine a little LED
Shine a little LED
geekinlibrariansclothing
 
python isn't just a snake
python isn't just a snakepython isn't just a snake
python isn't just a snake
geekinlibrariansclothing
 
Magic 8 ball prorgramming or structure is fun
Magic 8 ball prorgramming or structure is funMagic 8 ball prorgramming or structure is fun
Magic 8 ball prorgramming or structure is fun
geekinlibrariansclothing
 
Little bit of scratch
Little bit of scratchLittle bit of scratch
Little bit of scratch
geekinlibrariansclothing
 
Let there be light
Let there be lightLet there be light
Let there be light
geekinlibrariansclothing
 
Introduction to pi
Introduction to piIntroduction to pi
Introduction to pi
geekinlibrariansclothing
 
Course set three full notes
Course set three full notesCourse set three full notes
Course set three full notes
geekinlibrariansclothing
 
Genre queer super slides (1)
Genre queer super slides (1)Genre queer super slides (1)
Genre queer super slides (1)
geekinlibrariansclothing
 

More from geekinlibrariansclothing (8)

Shine a little LED
Shine a little LEDShine a little LED
Shine a little LED
 
python isn't just a snake
python isn't just a snakepython isn't just a snake
python isn't just a snake
 
Magic 8 ball prorgramming or structure is fun
Magic 8 ball prorgramming or structure is funMagic 8 ball prorgramming or structure is fun
Magic 8 ball prorgramming or structure is fun
 
Little bit of scratch
Little bit of scratchLittle bit of scratch
Little bit of scratch
 
Let there be light
Let there be lightLet there be light
Let there be light
 
Introduction to pi
Introduction to piIntroduction to pi
Introduction to pi
 
Course set three full notes
Course set three full notesCourse set three full notes
Course set three full notes
 
Genre queer super slides (1)
Genre queer super slides (1)Genre queer super slides (1)
Genre queer super slides (1)
 

Recently uploaded

PCOS corelations and management through Ayurveda.
PCOS corelations and management through Ayurveda.PCOS corelations and management through Ayurveda.
PCOS corelations and management through Ayurveda.
Dr. Shivangi Singh Parihar
 
C1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptx
C1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptxC1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptx
C1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptx
mulvey2
 
World environment day ppt For 5 June 2024
World environment day ppt For 5 June 2024World environment day ppt For 5 June 2024
World environment day ppt For 5 June 2024
ak6969907
 
Executive Directors Chat Leveraging AI for Diversity, Equity, and Inclusion
Executive Directors Chat  Leveraging AI for Diversity, Equity, and InclusionExecutive Directors Chat  Leveraging AI for Diversity, Equity, and Inclusion
Executive Directors Chat Leveraging AI for Diversity, Equity, and Inclusion
TechSoup
 
Pengantar Penggunaan Flutter - Dart programming language1.pptx
Pengantar Penggunaan Flutter - Dart programming language1.pptxPengantar Penggunaan Flutter - Dart programming language1.pptx
Pengantar Penggunaan Flutter - Dart programming language1.pptx
Fajar Baskoro
 
Chapter 4 - Islamic Financial Institutions in Malaysia.pptx
Chapter 4 - Islamic Financial Institutions in Malaysia.pptxChapter 4 - Islamic Financial Institutions in Malaysia.pptx
Chapter 4 - Islamic Financial Institutions in Malaysia.pptx
Mohd Adib Abd Muin, Senior Lecturer at Universiti Utara Malaysia
 
Azure Interview Questions and Answers PDF By ScholarHat
Azure Interview Questions and Answers PDF By ScholarHatAzure Interview Questions and Answers PDF By ScholarHat
Azure Interview Questions and Answers PDF By ScholarHat
Scholarhat
 
বাংলাদেশ অর্থনৈতিক সমীক্ষা (Economic Review) ২০২৪ UJS App.pdf
বাংলাদেশ অর্থনৈতিক সমীক্ষা (Economic Review) ২০২৪ UJS App.pdfবাংলাদেশ অর্থনৈতিক সমীক্ষা (Economic Review) ২০২৪ UJS App.pdf
বাংলাদেশ অর্থনৈতিক সমীক্ষা (Economic Review) ২০২৪ UJS App.pdf
eBook.com.bd (প্রয়োজনীয় বাংলা বই)
 
How to Manage Your Lost Opportunities in Odoo 17 CRM
How to Manage Your Lost Opportunities in Odoo 17 CRMHow to Manage Your Lost Opportunities in Odoo 17 CRM
How to Manage Your Lost Opportunities in Odoo 17 CRM
Celine George
 
Advanced Java[Extra Concepts, Not Difficult].docx
Advanced Java[Extra Concepts, Not Difficult].docxAdvanced Java[Extra Concepts, Not Difficult].docx
Advanced Java[Extra Concepts, Not Difficult].docx
adhitya5119
 
How to Fix the Import Error in the Odoo 17
How to Fix the Import Error in the Odoo 17How to Fix the Import Error in the Odoo 17
How to Fix the Import Error in the Odoo 17
Celine George
 
ISO/IEC 27001, ISO/IEC 42001, and GDPR: Best Practices for Implementation and...
ISO/IEC 27001, ISO/IEC 42001, and GDPR: Best Practices for Implementation and...ISO/IEC 27001, ISO/IEC 42001, and GDPR: Best Practices for Implementation and...
ISO/IEC 27001, ISO/IEC 42001, and GDPR: Best Practices for Implementation and...
PECB
 
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2023-2024 (CÓ FI...
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2023-2024 (CÓ FI...BÀI TẬP BỔ TRỢ TIẾNG ANH 8 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2023-2024 (CÓ FI...
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2023-2024 (CÓ FI...
Nguyen Thanh Tu Collection
 
PIMS Job Advertisement 2024.pdf Islamabad
PIMS Job Advertisement 2024.pdf IslamabadPIMS Job Advertisement 2024.pdf Islamabad
PIMS Job Advertisement 2024.pdf Islamabad
AyyanKhan40
 
Your Skill Boost Masterclass: Strategies for Effective Upskilling
Your Skill Boost Masterclass: Strategies for Effective UpskillingYour Skill Boost Masterclass: Strategies for Effective Upskilling
Your Skill Boost Masterclass: Strategies for Effective Upskilling
Excellence Foundation for South Sudan
 
What is Digital Literacy? A guest blog from Andy McLaughlin, University of Ab...
What is Digital Literacy? A guest blog from Andy McLaughlin, University of Ab...What is Digital Literacy? A guest blog from Andy McLaughlin, University of Ab...
What is Digital Literacy? A guest blog from Andy McLaughlin, University of Ab...
GeorgeMilliken2
 
LAND USE LAND COVER AND NDVI OF MIRZAPUR DISTRICT, UP
LAND USE LAND COVER AND NDVI OF MIRZAPUR DISTRICT, UPLAND USE LAND COVER AND NDVI OF MIRZAPUR DISTRICT, UP
LAND USE LAND COVER AND NDVI OF MIRZAPUR DISTRICT, UP
RAHUL
 
A Independência da América Espanhola LAPBOOK.pdf
A Independência da América Espanhola LAPBOOK.pdfA Independência da América Espanhola LAPBOOK.pdf
A Independência da América Espanhola LAPBOOK.pdf
Jean Carlos Nunes Paixão
 
Film vocab for eal 3 students: Australia the movie
Film vocab for eal 3 students: Australia the movieFilm vocab for eal 3 students: Australia the movie
Film vocab for eal 3 students: Australia the movie
Nicholas Montgomery
 
The basics of sentences session 6pptx.pptx
The basics of sentences session 6pptx.pptxThe basics of sentences session 6pptx.pptx
The basics of sentences session 6pptx.pptx
heathfieldcps1
 

Recently uploaded (20)

PCOS corelations and management through Ayurveda.
PCOS corelations and management through Ayurveda.PCOS corelations and management through Ayurveda.
PCOS corelations and management through Ayurveda.
 
C1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptx
C1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptxC1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptx
C1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptx
 
World environment day ppt For 5 June 2024
World environment day ppt For 5 June 2024World environment day ppt For 5 June 2024
World environment day ppt For 5 June 2024
 
Executive Directors Chat Leveraging AI for Diversity, Equity, and Inclusion
Executive Directors Chat  Leveraging AI for Diversity, Equity, and InclusionExecutive Directors Chat  Leveraging AI for Diversity, Equity, and Inclusion
Executive Directors Chat Leveraging AI for Diversity, Equity, and Inclusion
 
Pengantar Penggunaan Flutter - Dart programming language1.pptx
Pengantar Penggunaan Flutter - Dart programming language1.pptxPengantar Penggunaan Flutter - Dart programming language1.pptx
Pengantar Penggunaan Flutter - Dart programming language1.pptx
 
Chapter 4 - Islamic Financial Institutions in Malaysia.pptx
Chapter 4 - Islamic Financial Institutions in Malaysia.pptxChapter 4 - Islamic Financial Institutions in Malaysia.pptx
Chapter 4 - Islamic Financial Institutions in Malaysia.pptx
 
Azure Interview Questions and Answers PDF By ScholarHat
Azure Interview Questions and Answers PDF By ScholarHatAzure Interview Questions and Answers PDF By ScholarHat
Azure Interview Questions and Answers PDF By ScholarHat
 
বাংলাদেশ অর্থনৈতিক সমীক্ষা (Economic Review) ২০২৪ UJS App.pdf
বাংলাদেশ অর্থনৈতিক সমীক্ষা (Economic Review) ২০২৪ UJS App.pdfবাংলাদেশ অর্থনৈতিক সমীক্ষা (Economic Review) ২০২৪ UJS App.pdf
বাংলাদেশ অর্থনৈতিক সমীক্ষা (Economic Review) ২০২৪ UJS App.pdf
 
How to Manage Your Lost Opportunities in Odoo 17 CRM
How to Manage Your Lost Opportunities in Odoo 17 CRMHow to Manage Your Lost Opportunities in Odoo 17 CRM
How to Manage Your Lost Opportunities in Odoo 17 CRM
 
Advanced Java[Extra Concepts, Not Difficult].docx
Advanced Java[Extra Concepts, Not Difficult].docxAdvanced Java[Extra Concepts, Not Difficult].docx
Advanced Java[Extra Concepts, Not Difficult].docx
 
How to Fix the Import Error in the Odoo 17
How to Fix the Import Error in the Odoo 17How to Fix the Import Error in the Odoo 17
How to Fix the Import Error in the Odoo 17
 
ISO/IEC 27001, ISO/IEC 42001, and GDPR: Best Practices for Implementation and...
ISO/IEC 27001, ISO/IEC 42001, and GDPR: Best Practices for Implementation and...ISO/IEC 27001, ISO/IEC 42001, and GDPR: Best Practices for Implementation and...
ISO/IEC 27001, ISO/IEC 42001, and GDPR: Best Practices for Implementation and...
 
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2023-2024 (CÓ FI...
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2023-2024 (CÓ FI...BÀI TẬP BỔ TRỢ TIẾNG ANH 8 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2023-2024 (CÓ FI...
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2023-2024 (CÓ FI...
 
PIMS Job Advertisement 2024.pdf Islamabad
PIMS Job Advertisement 2024.pdf IslamabadPIMS Job Advertisement 2024.pdf Islamabad
PIMS Job Advertisement 2024.pdf Islamabad
 
Your Skill Boost Masterclass: Strategies for Effective Upskilling
Your Skill Boost Masterclass: Strategies for Effective UpskillingYour Skill Boost Masterclass: Strategies for Effective Upskilling
Your Skill Boost Masterclass: Strategies for Effective Upskilling
 
What is Digital Literacy? A guest blog from Andy McLaughlin, University of Ab...
What is Digital Literacy? A guest blog from Andy McLaughlin, University of Ab...What is Digital Literacy? A guest blog from Andy McLaughlin, University of Ab...
What is Digital Literacy? A guest blog from Andy McLaughlin, University of Ab...
 
LAND USE LAND COVER AND NDVI OF MIRZAPUR DISTRICT, UP
LAND USE LAND COVER AND NDVI OF MIRZAPUR DISTRICT, UPLAND USE LAND COVER AND NDVI OF MIRZAPUR DISTRICT, UP
LAND USE LAND COVER AND NDVI OF MIRZAPUR DISTRICT, UP
 
A Independência da América Espanhola LAPBOOK.pdf
A Independência da América Espanhola LAPBOOK.pdfA Independência da América Espanhola LAPBOOK.pdf
A Independência da América Espanhola LAPBOOK.pdf
 
Film vocab for eal 3 students: Australia the movie
Film vocab for eal 3 students: Australia the movieFilm vocab for eal 3 students: Australia the movie
Film vocab for eal 3 students: Australia the movie
 
The basics of sentences session 6pptx.pptx
The basics of sentences session 6pptx.pptxThe basics of sentences session 6pptx.pptx
The basics of sentences session 6pptx.pptx
 

Magic 8 ball putting it all together

  • 1. 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 prints 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 still interpreted as a
  • 2. 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 consistently indented. Python allows us to do just about anything we like within a function definition, 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
  • 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 question, 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 existing 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 time (perhaps for dramatic tension?), and if you choose to do so, be sure to load the time- related functions. >>> import time >>> def delay(howLong): for x in range(0, howLong): print('...thinking...') time.sleep(1) >>> def revealAnswer(question, answer, thinkingTime): print('Considering your question: ' + question) delay(thinkingTime) print('The Magic 8-ball has spoken! The answer you seek is this:') print(answer)
  • 4. Next, we need a way to allow the user to ask a question. We want to be able to do this over and over again, so another function is in order. This one will be simple. >>> def askAQuestion(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 questions as we like, or a certain number of questions. We also need to make sure that we initialize the question to something, so the program knows it exists. >>> question = 'none yet' >>> while (question != 'exit'): question = askAQuestion("What is your question? ") if question != "exit": answer = pickAnAnswer(answers) revealAnswer(question, answer, 1) What is your question? --> Should I exit? Considering your question: Should I exit? ...thinking... The Magic 8-ball has spoken! The answer you seek is this: Ask again What is your question? --> Should I exit? Considering your question: Should I exit? ...thinking... The Magic 8-ball has spoken! The answer you seek is this: Maybe What is your question? --> How about now? Considering your question: How about now? ...thinking... The Magic 8-ball has spoken! The answer you seek is this: Orange What is your question? --> Um, should I exit now? Considering your question: Um, should I exit now? ...thinking... The Magic 8-ball has spoken! The answer you seek is this: 73% chance What is your question? --> Okay, how about now? Considering your question: Okay, how about now? ...thinking... The Magic 8-ball has spoken! The answer you seek is this: Yes What is your question? --> exit >>>
  • 5. Here is the complete text of the program. import random import time answers = ['Yes', 'No', 'Maybe', 'Ask again', '73% chance', 'Orange', “Batman”, 42] def askAQuestion(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...') time.sleep(1) def revealAnswer(question, answer, thinkingTime): print('Considering your question: ' + question) delay(thinkingTime) print('The Magic 8-ball has spoken! The answer you seek is this:') print(answer) question = 'none yet' while (question != 'exit'):
  • 6. question = askAQuestion("What is your question? ") if question != “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.