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:

  • random value: number generated from set of numbers
  • uses for random vaules: games, cryptography, sampling
  • use random package for python to generate random values
  • for random int in range a,b, use random.randint(a,b)

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

Why do we need Random Values for code?

Random values can be used in coding:

import random
random_number = random.randint(1,100)
print(random_number)
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))

Challenge #1

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

import random
def coinflip():
    result = ""
    num = random.randint(0,2)
    if num == 0:
        result = "Heads"
    else:
        result = "Tails"
    print(result)

coinflip()
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 dectobin(dec1):
    bin = ""
    i = 7

    while i >= 0:
        if dec1 % (2**i) == dec1:
            bin = bin + "0"
            i -= 1
        else:
            bin = bin + "1"
            dec1 -= 2**i
            i -= 1

    print(bin)

def dectohex(dec2):
    hex = ""
    while dec2 > 0:
        x = int(dec2 % 16)
        if x < 10:
            hex = hex + str(x)
        if x == 10:
            hex = hex + "a"
        if x == 11:
            hex = hex + "b"
        if x == 12:
            hex = hex + "c"
        if x == 13:
            hex = hex + "d"
        if x == 14:
            hex = hex + "e"
        if x == 15:
            hex = hex + "f"
        dec2 = (dec2 - x) / 16

    hex2 = ""
    j = len(hex) - 1
    while j >= 0:
        hex2 = hex2 + hex[j]
        j -= 1

    print(hex2)

dectobin(200)
dectohex(200)
11001000
c8