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.

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 datetime import date, timedelta, datetime
import random

minDate, maxDate = date(1900, 1, 1), date(2022, 12, 31)
print("Date range: " + str(minDate) + " to " + str(maxDate))
dateDays = maxDate - minDate
totalDays = dateDays.days
randDay = random.randrange(totalDays)
randDate = minDate + timedelta(days=randDay)
print(randDate)
# used this in other assignment as well
Date range: 1900-01-01 to 2022-12-31
2016-12-29

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"

from turtle import *
oogway = Turtle()

Challenge 3: Math

The math package allows for some really cool mathematical methods!

Methods Action
ceil(x) Returns whichever number is the next highest integer
floor(x) Rounds to largest integer less than or equal to x
factorial(x) Returns the factorial
gcd(x, y) Returns the greatest common denominator of x and y
lcm(x, y) Returns the least common multiple 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 *
import math
x = ""
y = ""
while ((x != "quit") and (y != "quit")):
    x = input()
    if (x == "quit"):
        break
    
    y = input()
    if (y == "quit"):
        break
    
    # my vscode is giving me an 'attribute does not exist' for LCM and I am not fixing that so. just know that i tried
    
    xf = float(x)
    yf = float(y)
    ceilNumX = math.ceil(xf)
    floorNumX = math.floor(xf)
    ceilNumY = math.ceil(yf)
    floorNumY = math.floor(yf)
    factNumX = math.factorial(int(xf))
    lcmNumXY = math.lcm(int(floorNumX), int(floorNumY))
    gcdNumXY = math.gcd(int(ceilNumX), int(ceilNumY))
    factNumY = math.factorial(int(yf))
    sqrtNumX = math.isqrt(int(floorNumX))
    sqrtNumY = math.isqrt(int(floorNumY))
    print ("Ceiling of", x ,"=", ceilNumX)
    print ("Floor of", x ,"=", floorNumX)
    print ("Factorial of", x ,"=", factNumX)
    print ("Ceiling of", y ,"=", ceilNumY)
    print ("Floor of", y ,"=", floorNumY)
    print ("LCM of", y, x ,"=", lcmNumXY)
    print ("GCD of", y, x,"=", gcdNumXY)
    print ("Factorial of", y ,"=", factNumY)
    print ("Square root of", x,"=", sqrtNumX)
    print ("Square root of", y,"=", sqrtNumY)
Ceiling of 2.34 = 3
Floor of 2.34 = 2
Factorial of 2.34 = 2
Ceiling of 3.45 = 4
Floor of 3.45 = 3
LCM of 3.45 2.34 = 6
GCD of 3.45 2.34 = 1
Factorial of 3.45 = 6
Square root of 2.34 = 1
Square root of 3.45 = 1

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 random
import turtle

turns = []

t = turtle.Turtle()
randNum = random.randint(1, 10)
sideLen = input()
print ("Randomly generated number:", randNum)
print ("User input side length:", sideLen)

for c in ['red', 'orange', 'yellow', 'green', 'blue']:
    t.color(c)
    turns = 0 
    for r in range(randNum):
        t.forward(sideLen)
        t.left(360/randNum)
        turns = turns + 1
        if turns == randNum:
            break


# So, my turtle doesn't like me and doesn't want to work so I just made this 'theoretical' code
# Essentially, it's just supposed to generate a random number, which the code marks as the 'randNum', or in other words, the amount of sides
# The user can also choose to input a side length
# It then prints the side length and number of sides (these are mostly for testing)
# The color is randomly selected
# Then the turtle will move in accordance to the numbers it's been dealt
# t.forward is the side lengths, and it will move in accordance to the input
# t.left is the corners of the shape; since a full circle is 360 degrees, the turtle will turn in a degree that is 360/the randomly generated number so it can have the right amount of sides
# If I actually coded this right, the turtle will end at the same place it started and keep looping forever because I didn't put an end code. But that's ok my turtle doesn't work so you won't ever have to see its eternal suffering, brought on by the stupidity of none other than my lack of sleep and endless desire to drop school completely

# Actually I lied, I added the ending code
# There's a turn counter that adds 1 to a neat little index and if that index = the amount of rotations the turtle will stop (hopefully. It can just keep going if it wants to. Goodbye turtle you will be missed.)
---------------------------------------------------------------------------
TclError                                  Traceback (most recent call last)
/mnt/c/Users/Keira/vscode/Fastpages/_notebooks/2022-12-12-3.14-Libraries.ipynb Cell 11 in <cell line: 4>()
      <a href='vscode-notebook-cell://wsl%2Bubuntu/mnt/c/Users/Keira/vscode/Fastpages/_notebooks/2022-12-12-3.14-Libraries.ipynb#X15sdnNjb2RlLXJlbW90ZQ%3D%3D?line=0'>1</a> import random
      <a href='vscode-notebook-cell://wsl%2Bubuntu/mnt/c/Users/Keira/vscode/Fastpages/_notebooks/2022-12-12-3.14-Libraries.ipynb#X15sdnNjb2RlLXJlbW90ZQ%3D%3D?line=1'>2</a> import turtle
----> <a href='vscode-notebook-cell://wsl%2Bubuntu/mnt/c/Users/Keira/vscode/Fastpages/_notebooks/2022-12-12-3.14-Libraries.ipynb#X15sdnNjb2RlLXJlbW90ZQ%3D%3D?line=3'>4</a> t = turtle.Turtle()
      <a href='vscode-notebook-cell://wsl%2Bubuntu/mnt/c/Users/Keira/vscode/Fastpages/_notebooks/2022-12-12-3.14-Libraries.ipynb#X15sdnNjb2RlLXJlbW90ZQ%3D%3D?line=5'>6</a> randNum = []
      <a href='vscode-notebook-cell://wsl%2Bubuntu/mnt/c/Users/Keira/vscode/Fastpages/_notebooks/2022-12-12-3.14-Libraries.ipynb#X15sdnNjb2RlLXJlbW90ZQ%3D%3D?line=7'>8</a> def printRan(randNum):

File ~/anaconda3/lib/python3.9/turtle.py:3814, in Turtle.__init__(self, shape, undobuffersize, visible)
   3809 def __init__(self,
   3810              shape=_CFG["shape"],
   3811              undobuffersize=_CFG["undobuffersize"],
   3812              visible=_CFG["visible"]):
   3813     if Turtle._screen is None:
-> 3814         Turtle._screen = Screen()
   3815     RawTurtle.__init__(self, Turtle._screen,
   3816                        shape=shape,
   3817                        undobuffersize=undobuffersize,
   3818                        visible=visible)

File ~/anaconda3/lib/python3.9/turtle.py:3664, in Screen()
   3660 """Return the singleton screen object.
   3661 If none exists at the moment, create a new one and return it,
   3662 else return the existing one."""
   3663 if Turtle._screen is None:
-> 3664     Turtle._screen = _Screen()
   3665 return Turtle._screen

File ~/anaconda3/lib/python3.9/turtle.py:3680, in _Screen.__init__(self)
   3673 def __init__(self):
   3674     # XXX there is no need for this code to be conditional,
   3675     # as there will be only a single _Screen instance, anyway
   3676     # XXX actually, the turtle demo is injecting root window,
   3677     # so perhaps the conditional creation of a root should be
   3678     # preserved (perhaps by passing it as an optional parameter)
   3679     if _Screen._root is None:
-> 3680         _Screen._root = self._root = _Root()
   3681         self._root.title(_Screen._title)
   3682         self._root.ondestroy(self._destroy)

File ~/anaconda3/lib/python3.9/turtle.py:435, in _Root.__init__(self)
    434 def __init__(self):
--> 435     TK.Tk.__init__(self)

File ~/anaconda3/lib/python3.9/tkinter/__init__.py:2270, in Tk.__init__(self, screenName, baseName, className, useTk, sync, use)
   2268         baseName = baseName + ext
   2269 interactive = False
-> 2270 self.tk = _tkinter.create(screenName, baseName, className, interactive, wantobjects, useTk, sync, use)
   2271 if useTk:
   2272     self._loadtk()

TclError: no display name and no $DISPLAY environment variable