What you will learn
- Define and identify: function, arguments, calling, importing, returning
- Call the built-in
randintfunction, using arguments - Utilize code other people have written in the Python documentation
- Understand the difference between printing and returning
Reading
- Associated Reading - section 3.1 of Book
Do Now
In your Console
Type the following code
import random
random.randint(0, 3)
random.randint(0, 3)
print(random.randint(0, 3))
print(random.randint(0, 3))
print(random.randint(0, 3))
In your Notebook
Respond to the following
- What does randint do?
- What do the values
0and3do? Try changing those numbers, rerun the program, and write down what changed. - What is the difference between
random.randint(0,3)andprint(random.randint(0,3))?
Lab
Practice importing random** — Use randint with different arguments. Simulate a dice roll, printing out to the user what number they rolled.
Look at the documentation of the random library — Experiment with another function (not randint) that returns a value.
Create a program that simulates a magic 8-ball
- Store all of the 8-ball’s possible responses (shown below) in a list
- Have the program prompt the user to ask the magic 8-ball a question
- then return and print a random response.
Magic 8-Ball Response Examples
- Outlook is good
- Ask again later
- Yes
- No
- Most likely no
- Most likely yes
- Maybe
- Outlook is not good
Video Explanation
Bonus
Research the math library and create a program that finds the length of the hypotenuse of a right triangle given two sides.
Check your understanding
Pick an answer for each question. You can try again until you get it right.
1. What does random.randint(0, 3) do?
- Always returns 3
- Prints the numbers 0 through 3
- Returns a random whole number from 0 to 3, including both ends
- Returns a random decimal between 0 and 3
It picks a random integer between the two arguments, inclusive, and gives it back to the caller.
2. What must you do before you can call random.randint?
- Write
import randomfirst - Define
randintyourself withdef - Nothing, every function is always available
- Print the arguments
Code from the random library has to be imported before you can use it.
3. If a program contains only the line random.randint(1, 6) (no print), what do you see when it runs?
- A random number from 1 to 6
- Nothing, the value is returned but never displayed
- An error
- The text
randint
A returned value is not shown unless you print it or store it.
