Unit 3.15 Random Values Student Copy
Here is our lesson about random values!
- What are Random Values?
- Why do we need Random Values for code?
- Random values can be used in coding:
- Challenge #1
- Homework
Purpose/Objectives: Teach student how to implement randomness into their code to make their code simulate real life situations.
In this lesson students will learn:
- How to import random to python
- How to use random with a list or number range
- How to code randomness in everyday scenarios
ADD YOUR ADDITIONAL NOTES HERE:
- Lists make it so every number has an equal chance of being picked if chosen at random.
- Some topics that use luck are rolling dice, cryptography, etc.
Random Values are a number generated using a large set of numbers and a mathematical algorithm which gives equal probability to all number occuring
Each Result from randomization is equally likely to occur Using random number generation in a program means each execution may produce a different result
What are Examples of Random outputs in the world? Add a few you can think of.
- Ex: Marbles
- Cryptography
- Dice
- Statistics
- The Lottery
import random
random_number = random.randint(1,100)
print(random_number)
import random
def randomlist():
list = ["apple", "banana", "cherry", "blueberry"]
element = random.choice(list)
print(element)
randomlist()
Real Life Examples: Dice Roll
import random
for i in range(3):
roll = random.randint(1,6)
print("Roll " + str(i + 1) + ":" + str(roll))
from random import randint as r
def coinflip():
roll = r(1,2)
if roll == 1:
return "heads"
else:
return "tails"
print(coinflip())
EXTRA: Create a function that will randomly select 5 playing Cards and check if the 5 cards are a Royal Flush
import random as r
x = r.randint(0, 255)
def decToBin(N):
return bin(N)
def decToHex(N):
i = 0
hexDec = []
while N!=0:
rm = N % 16
if rm<10:
rm = rm+48
else:
rm = rm+55
hexDec.insert(i, chr(rm))
i = i+1
N = int(N / 16)
print("\nEquivalent Hexadecimal Value = ", end="")
i = i-1
while i>=0:
print(end=hexDec[i])
i = i-1
print("Original number: " + str(x))
print("\nBinary: " + str(decToBin(x)))
decToHex(x)