Unit 3.14 Libraries Lesson
Here is our lesson about libraries!
- Libraries
- Challenge 1: Basic Libraries
- Challenge 2: Turtle
- Challenge 3: Math
- Homework: Putting it all together(complete only after the random values lesson)
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
- Find a python package on the internet and import it
- Choose a method from the package and import only the method
- 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
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)
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.)