Purpose: Help students streamline and make their coding experience easier through built in packages and methods from a library
Objective: By the end of the lesson, students should be able to fluently use methods from the turtle and math packages, and be able to look up documentation for any python package and us it.

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 "import", 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 math import sin as sine
pi = 3.1415296535
print(sine(pi/3))
0.8660149035785147

Challenge 2: Turtle

Turtle is a python drawing library 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) when given a decimal number, it will return the next highest integer 10.1 is 11 and 10.9 is also 11
Floor rounds to largest intefer less than or equal to x
factorial(x) returns the factorial
gcd (x) returns the greatest common denominator of x and y
lcm(x,y) least common multiple
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
import math
from math import *

x = float(input("#"))
y = float(input("#"))
print("lcm numbers is " + str(lcm(floor(x), floor(y))))
print("gcf numbers is " + str(gcd(ceil(x), ceil(y))))
print("factorial of x is " + str(factorial(floor(x))))
print("factorial of y is " + str(factorial(floor(y))))
print("the square root of x is " + str(sqrt(x)))
lcm numbers is 56
gcf numbers is 1
factorial of x is 5040
factorial of y is 40320
the square root of x is 2.6457513110645907

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!

Unit 3.15 Random Values Student Copy

Here is our lesson about random values!

  • toc:true- comments: true
  • categories: [Week-13,Big-Idea-3]
  • image: /images/college-board-logo.png

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:

  • every number in the list has an equal chance of occuring
  • rng topics - dice, stats, cryptography

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
  • stats
  • cryptography

Why do we need Random Values for code? Sometimes, we need to have random outcomes of a certain scenario.

Random values can be used in coding:

import random
random_number = random.randint(1,100)
print(random_number)
71
def randomlist():
    list = ["apple", "banana", "cherry", "blueberry"]
    element = random.choice(list)
    print(element)
randomlist()
banana
import random
for i in range(3):
    roll = random.randint(1,6)
    print("Roll " + str(i + 1) + ":" + str(roll))
Roll 1:6
Roll 2:5
Roll 3:1

Challenge #1

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

def coinflip():
    return "heads" if random.randint(1,2) == 1 else "tails"

print(coinflip())
heads

Homework

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

x = random.randint(0, 255)

def DecToBinary(x):
    i = 7
    binary = ""
    while i >= 0:
        if x % (2**i) == x:
            binary += "0"
            i -= 1
        else:
            binary += "1"
            x -= 2**i
            i -= 1
    return binary

print("Decimal number:", x)
print("Binary:", DecToBinary(x))
Decimal number: 13
Binary: 00001101
def DecToHex(x):
    hexlist = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F']
    hexa = []
    hexadec = ''
    while x > 0:
        x, ind = divmod(x, 16)
        hexa.append(hexlist[ind])
    i = (len(hexa) - 1)
    while i >= 0:
        hexadec += hexa[i]
        i -= 1
    return hexadec

y = random.randint(0, 16777215)
print("Decimal:", y)
print("Binary:", DecToHex(y))
Decimal: 1941044
Binary: 1D9E34

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

I tried doing the card thing, but I don't know how to continue after this

import random
suits = ['Spades', 'Clubs', 'Hearts', 'Diamonds']
cards = ['2', '3', '4', '5', '6', '7', '8', '9', '10', 'Jack', 'Queen', 'King', 'Ace']
deck = []
for suit in suits:
    for card in cards:
        info = ((card + ' of ' + suit), card, suit)
        deck.append(info)
random.shuffle(deck)
import random

dictionary = {
    1: 31,
    2: 28,
    3: 31,
    4: 30,
    5: 31,
    6: 30,
    7: 31,
    8: 31,
    9: 30,
    10: 31,
    11: 30,
    12: 31,
}


uday = int(input("a day"))
umonth = int(input("a month"))
year = int(input("a year"))
udate = str(umonth) + "-" + str(uday) + "-" + str(year)
print(udate)

rmonth = random.randint(1,12)
rdayrange = dictionary.get(rmonth)
rday = random.randint(0,rdayrange)
rdate = str(rmonth) + "-" + str(rday) + "-" + str(year)
print(rdate)

def days(months,days):
    start = 0

    for i in range (1,months):
        start += (dictionary.get(i))

    start += days
    return(start)

uabs = days(umonth,uday)
rabs = days(rmonth,rday)
dist = abs(uabs - rabs)

print("There are ..." + str(dist) + " days between " + udate + " and " + rdate)
6/2/2000
3/15/2000
There are ...79 days between 6/2/2000 and 3/15/2000