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 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.

Personal Notes

  • A star (*) is also known as a wildcard character. It will automatically grab everything under a certain subset.
  • There are many different python modules for many different tasks, there is no need in reinventing the wheel.
  • Built-in methods and packages exist within python, and we can directly use those without importing
  • There are different ways to import a package, which methods such as the normal import statement, from package statement, even importing a method or module underneath a different name.

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 s
pi = 3.1415926535
print(s(pi/6))
0.4999999999870395

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) Rounds to the nearest integer greater than a number
floor(x) rounds to largest intefer less than or equal to x
factorial(x) Returns the factorial, or sequence of products of numbers before the input
gcd(x) returns the greatest common denominator of x and y
lcm(x,y) returns the least common denominator of x and y
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 *
inpt = input("Enter your two decimal numbers: ").split(" ")
num1, num2 = float(inpt[0]), float(inpt[1])
print("Ceiling of two numbers:", ceil(num1), ceil(num2))
print("Floor of two numbers:", floor(num1), floor(num2))
print("Least Common Multiple of two numbers rounded down:", lcm(floor(num1),floor(num2)))
print("Greatest Common Divisor of two numbers rounded up:", gcd(ceil(num1),ceil(num2)))
print("Factorial of two numbers rounded down:", factorial(floor(num1)), factorial(floor(num2)))
print("Sine of the sum two numbers:", sin(num1 + num2))
Ceiling of two numbers: 18 20
Floor of two numbers: 17 19
Least Common Multiple of two numbers rounded down: 323
Greatest Common Divisor of two numbers rounded up: 2
Factorial of two numbers rounded down: 355687428096000 121645100408832000
Sine of the sum two numbers: -0.2946716015002508

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!

Item #1

Program to find the difference between two dates

import datetime
import random

days_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,
}


usr_date = input("Enter a date MM/DD/YYYY").split("/")
usr_day, usr_month, usr_year = int(usr_date[0]), int(usr_date[1]), int(usr_date[2])

def generateRandomDate(year):
    start = datetime.datetime(year, 1, 1)
    return start + datetime.timedelta(days=random.randint(1,364))

def calculateDistance(m1,d1,m2, d2):
    days = 0
    if m1 == m2:
        return d2-d1
    days += days_dictionary[m1] - d1
    month = m1 + 1
    while month != m2:
        days += days_dictionary[month]
        month += 1
    days += d2
    return days

random_date = generateRandomDate(usr_year)
random_month=random_date.month
random_day=random_date.day
if (random_month > usr_month or (random_month == usr_month and random_day > usr_day)):
    print("There are {0} days between your date of {1}/{2} and the random date of {3}/{4}".format(calculateDistance(usr_month, usr_day, random_month, random_day), usr_month, usr_day, random_month, random_day))
else:
    print("There are {0} days between your date of {1}/{2} and the random date of {3}/{4}".format(calculateDistance(random_month, random_day, usr_month, usr_day), usr_month, usr_day, random_month, random_day))
There are 288 days between your date of 13/12 and the random date of 3/30

Item 2

Program to convert a random number into a binary and then into hexadecimal

def DecimalToHex(num):
    hex_correlation = {
        0:"0",
        1:"1",
        2:"2",
        3:"3",
        4:"4",
        5:"5",
        6:"6",
        7:"7",
        8:"8",
        9:"9",
        10:"A",
        11:"B",
        12:"C",
        13:"D",
        14:"E",
        15:"F"
    }
    res = ""
    digits = 7
    while digits >= 0:
        if (num - 16 ** digits) >= 0:
            sub_res = 0
            while (num - 16 ** digits) >= 0:
                sub_res+=1
                num-=16 ** digits  
            res = res + str(hex_correlation[sub_res])
        else:
            res = res + "0"
        digits-=1  
    return res


num = random.randint(0,1000000000)
print("Random Number:", num)
print("Binary representation of random number:", bin(num)[2:])
print("Hexadecimal representation of random number:", DecimalToHex(num))
Random Number: 934222060
Binary representation of random number: 110111101011110001100011101100
Hexadecimal representation of random number: 37AF18EC

Extra

Drawing a polygon with random number of sides with turtle