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

What are Random Values?

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, coin flip, cards, hair colors and genes

Why do we need Random Values for code?

Random values can be used in coding for Games, Statistical Sampling, Cryptography, etc.

Random values can be used in coding:

import random
random_number = random.randint(1,100)
print(random_number)
51
def randomlist():
    list = ["apple", "banana", "cherry", "blueberry"]
    element = random.choice(list)
    print(element)
randomlist()
apple

Real Life Examples: Dice Roll

import random
for i in range(3):
    roll = random.randint(1,6)
    print("Roll " + str(i + 1) + ":" + str(roll))
Roll 1:2
Roll 2:1
Roll 3:2

Challenge #1

Write a function that will a simulate a coinflip and print the output

import random

def coinflip():         # def function 
    randomflip = random.randint(0, 1) # picks either 0 or 1 randomly (50/50 chance of either) 
    if randomflip == 0: # assigning 0 to be heads; if 0 is chosen then it will print, "Heads"
        print("Heads")
    else:
        if randomflip == 1: # assigning 1 to be tails; if 1 is chosen then it will print, "Tails"
            print("Tails")

# Tossing the coin 5 times:
t1 = coinflip()
t2 = coinflip()
t3 = coinflip()
t4 = coinflip()
t5 = coinflip()
Heads
Heads
Heads
Heads
Tails

EXTRA: Create a function that will randomly select 5 playing Cards and check if the 5 cards are a Royal Flush

Homework

Given a random decimal number convert it into binary as Extra convert it to hexidecimal as well.

def convert(n): 
    if n == 0:
        print("0")
    elif n == 1:
        print("1")
    else:
        binary = "" # define a string "" variable for storing binary digits; calculated below
        # divide the number (n) by 2, until it becomes 0, and store the remainder in the above string variable
        while int(n) > 0:
            binary += str(int(n%2)) # retreive the remainder, and keep appending to the string
            n = n / 2 # change the number to its quotient, then repeat
        print(binary[::-1]) # now the binary string has all the desired digits, but in reverse order
        # :: is how to reverse string
        
n = random.randint(1,100) # generates random number 1 to 100
convert(n) # perform the function
100011