Python KPRIDE: Random Numbers
star
star
star
star
star
Last updated 6 months ago
4 questions
Keywords
- Sequence: Lines of code are run in order they appear once.
- Integer: a whole number; a number that is not a fraction.
- Float / Real: A number with a decimal point
- Random number: A number that appears to have been selected randomly from a set
- Import random: Let's you use a library of code that focuses on random numbers
Predict and Run
Look at the code for each question.
What do you think will be the output?
What is the actual output?
1
What do you think will happen with this code:
import random
randomNumber = random.randint(1,6)
print("You rolled a ...")
print(randomNumber)
What do you think will happen with this code:
import random
randomNumber = random.randint(1,6)
print("You rolled a ...")
print(randomNumber)
Investigate
- Look at the code on the right.
- Run it and see what it does.
- Click on the pencil icon at the top to see the code again.
- Change the numbers inside randint( ) and see what happens.
- Does it still work if the number 1 is replaced?
Extend
Help:
print ( ) is used to output text
input( ) is used to get the user to type something
Variables store values that can change.
Name = Value here
e.g. myName = "John"
To store numbers in a variable use:
variableName = int(input())
1
Create a program that will ask the user for how many sides they want their dice to have using: int(input(" "))Then generate a number from 1 to that number.
Create a program that will ask the user for how many sides they want their dice to have using:
int(input(" "))
Then generate a number from 1 to that number.
1
Create a program that generates two random numbers between 1 and 6.
Add both of these numbers together and display the total.
Create a program that generates two random numbers between 1 and 6.
Add both of these numbers together and display the total.
1
Continue with the last code:Generate a third roll from 2 to 12.If that number is larger than the sum of the first two numbers, output "You lose". If it is lower, output "You win!".If it is the same, output "Draw".
Continue with the last code:
Generate a third roll from 2 to 12.
If that number is larger than the sum of the first two numbers, output "You lose". If it is lower, output "You win!".
If it is the same, output "Draw".