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:

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, dice

Why do we need Random Values for code?

random values can be used in coding:

  • games
  • statistical sampling
  • cryptography

Random values can be used in coding:

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

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:3
Roll 2:5
Roll 3:2

Challenge #1

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

def randomlist():
    list = ["heads", "tails"]
    element = random.choice(list)
    print(element)
randomlist()
heads

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

import random

def royal_flush():
  # create a list of suits
  suits = ["Clubs","Spades","Diamonds","Hearts"] 
  # create a list of card numbers
  numbers = [2,3,4,5,6,7,8,9,10,"J","Q","K","A"] 
  # store our 5 random cards
  cards = []
  # loop 5 times to generate 5 random cards
  for i in range(5):
    # create a random card number
    rand_number = random.choice(numbers) 
    # create a random suit
    rand_suit = random.choice(suits) 
    # add the random card to our list
    cards.append([rand_number,rand_suit]) 
  # check if the cards make a royal flush
  result = check_royal_flush(cards) 
  # print the cards and the result
  print(cards)
  print(result)

# function to check if the given cards make a royal flush
def check_royal_flush(cards):
  # set the initial result to false
  result = False
  # get the suit of the first card
  suit = cards[0][1]
  # set the initial card number
  card_number = 10
  # loop through the cards
  for card in cards:
    # check if the card suits match
    if card[1] == suit:
      # check if the card numbers are consecutive starting from 10
      if card[0] == card_number:
        # increment the card number
        card_number += 1
      # if the card numbers are not consecutive, return False
      else:
        return False
    # if the card suits don't match, return False
    else:
      return False
  # if all the cards match the suit and the numbers are consecutive, return True
  return True

# call the royal_flush function
royal_flush()
[['J', 'Diamonds'], [10, 'Hearts'], ['K', 'Diamonds'], ['K', 'Hearts'], [7, 'Spades']]
False

Homework

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

dec = float(input("Enter a decimal number: "))

print(bin(int(dec))[2:])

# decimal to hexidecimal

print(hex(int(dec))[2:])
110
6

fill in the blanks!

Libraries

Okay, so we've learned a lot of code, and all of you now can boast that you can code at least some basic programs in python. But, what about more advanced stuff? What if there's a more advanced program you don't know how to make? Do you need to make it yourself? Well, not always.

You've already learned about functions that you can write to reuse in your code in previous lessons. But,there are many others who code in python just like you. So why would you do again what someone has already done, and is available for any python user?

Packages allow a python user to import methods from a library, and use the methods in their code. Most libraries come with documentation on the different methods they entail and how to use them, and they can be found with a quick google search. methods are used with the following:

Note: a method from a package can only be used after the import statement.

Some libraries are always installed, such as those with the list methods which we have previously discussed. But others require a special python keyword called import. We will learn different ways to import in Challenge 1.

Sometimes we only need to import a single method from the package. We can do that with the word "from", followed by the package name, then the word import, then the method. This will alllow you to use the method without mentioning the package's name, unlike what we did before, however other methods from that package cannot be used. To get the best of both worlds you can use "*".

To import a method as an easier name, just do what we did first, add the word "as", and write the name you would like to use that package as.

Challenge 1: Basic Libraries

  1. Find a python package on the internet and import it
  2. Choose a method from the package and import only the method
  3. import the package as a more convenient name.
from random import randint
randint(2006,2022)
2020

Challenge 2: Turtle

Turtle is a python drawing package which allows you to draw all kinds of different shapes. It's ofter used to teach beginning python learners, but is really cool to use anywhere. Turtle employs a graphics package to display what you've done, but unfortunately it's kind of annoying to make work with vscode.
Use: repl.it
Click "+ Create", and for language, select "Python (with Turtle)"
Documentation
Task: Have fun with turtle! Create something that uses at least 2 lines of different lengths and 2 turns with different angles, and changes at least one setting about either the pen or canvas. Also use one command that isn't mentioned on the table below(there are a lot). Paste a screenshot of the code and the drawing from repl.it

Commands
forward(pixels)
right(degrees)
left(degrees)
setpos(x,y)
speed(speed)
pensize(size)
pencolor(color)

Note: Color should be within quotes, like "brown", or "red"

Challenge 3: Math

The math package allows for some really cool mathematical methods!

methods Action
ceil(x) will return whatever the next highest interger
x rounds to largest intefer less than or equal to x
factorial(x) reutrns the factorial
gcf(x,y) returns the greatest common denominator of x and y
lcm(x,y) returns the least common denominator
Challenge: Create a program which asks for a user input of two numbers, and returns the following:
  • each number rounded up
  • each number rounded down
  • the lcm of the rounded down numbers
  • the gcf of the rounded up numbers
  • the factorial of each number
  • something else using the math package!
    Documentation
from math import *
def coolmath(x, y):
    upx = ceil(x)
    upy = ceil(y)
    downx = floor(x)
    downy = floor(y)
    a = lcm(downx, downy)
    b = gcd(upx, upy)
    facx = factorial(abs(upx))
    facy = factorial(abs(upy))
    rootx = sqrt(abs(x))
    rooty = sqrt(abs(y))
    return(upx, upy, downx, downy, a, b, facx, facy, rootx, rooty)

x = input("Enter first number")
y = input("Enter second number")
coolmath(float(x), float(y))
(7, 2, 7, 2, 14, 1, 5040, 2, 2.6457513110645907, 1.4142135623730951)

Homework: Putting it all together(complete only after the random values lesson)

Option 1: Create a python program which generates a random number between 1 and 10, and use turtle to draw a regular polygon with that many sides. As a hint, remember that the total sum of all the angles in a polygon is (the number of sides - 2) * 180. Note: a regular polygon has all sides and angles the same size. Paste a screenshot of the code and the drawing from repl.it

Option 2: use the "datetime" package, and looking up documentation, create a program to generate 2 random dates and find the number of days between

Extra ideas: customize the settings, draw a picture, or something else!

import datetime

# Generate two random dates
date_1 = datetime.date(2020, 5, 6)
date_2 = datetime.date(2019, 3, 10)

# Find the difference between dates
difference = date_1 - date_2

# Print the number of days between the two dates
print("The number of days between the two dates is:", difference.days)
The number of days between the two dates is: 423