Python Basics Slides ÔÇô Ch3.2

Download Report

Transcript Python Basics Slides ÔÇô Ch3.2

[ slide 1 ]
Make a dice challenge!
This is a starter activity and should take 5 minutes
1. Log in to your computer
2. Open IDLE
3. Copy the code below in interactive mode
>>> import random
>>> random.randint(1,6)
(After pressing RETURN, Python gives you a number between 1 and 6.)
1. Now place your cursor back, somewhere in random.randint(1,6)
press RETURN and IDLE will copy the code for you to have another go.
[ slide 2 ]
Lesson Aims
In this lesson you are going to:
1. learn how to use the randint() function
2. learn how to use if, elif and else
3. Use the input() function in some different ways
4. finish the MyMagic8Ball game
5. Run a Python file
Vocabulary
script mode
module
Coding Time
1. Find your file called myMagic8Ball.py you saved last lesson.
(It should be in a Python Code folder inside Documents.)
2. Double click on the file to open it in IDLE.
3. Add the code from Code Box 3.3 (page 35) to the bottom of your file,
then check it carefully.
4. Add the code from Code Box 3.4 (page 37). Check it again.
5. Save your file.
If you are waiting:
Read page 36-40 in Python Basics.
[ slide 3 ]
[ slide 4 ]
Code Analysis
print("Welcome
# use the randint()
to My8Ball.")
function to select the correct answer
choice=random.randint(1, 8)
# get
if choice
the users
== 1:
question
question
answer=ans1
= input("Ask me for advice then press ENTER to shake me.\n")
elif choice == 2:
print("shaking
answer=ans2
...\n" * 4)
etc. etc.
elif choice == 7:
answer=ans7
else:
answer=ans8
# print the answer to the screen
print(answer)
input("\n\nPress the RETURN key to finish.")
[ slide 5 ]
Running programs in script mode
1. Make sure the file is saved.
2. With myMagic8Ball.py open choose Run Module from the Run menu
3. The program will run in the interactive mode window
which now acts as a console.
If it does not work properly:
Carefully compare your code with the complete script in Code Box 3.5
(page 41 and 42)
When fnished:
Try out the Ideas on page 43 and 44.
[ slide 6 ]
Homework
1. Make a copy of myMagic8Ball.py
2. Rename it as myFortuneCookie.py
3. Using this file as a template re-write it so that it works like a fortune
cookie.
[ slide 7 ]
Lesson Summary
In this lesson you have:
1. learnt how to use the randint() function
2. learnt how to use if, elif and else
3. Used the input() function in some different ways
4. finishe the MyMagic8Ball game
5. Run a Python file
Vocabulary
What is a module?
A file that stores useful functions
What must we do to use functions from a module?
import the module
Can you name three ways we can use the input() function?
Answers on the last slide
[ slide 8 ]
The input() function
# pause a program until a user is ready:
input("Please press ENTER to continue.")
# get and store a user’s keyboard input
question = input("Please tell me your name.\n")
# provide a tidy way of ending a program:
input("\n\nPress the RETURN key to finish.")