Unit 7 · Borrowing Code · Lesson 53 of 57
Don't Reinvent the Wheel
Don't reinvent the wheel
Say you need the square root of something. You could write your own square root function. Or...
import math
print(math.sqrt(144))
print(math.pi)
12.0
3.141592653589793
import math borrows a whole bunch of code that someone else already wrote and tested, called a module. Python comes with tons of them built in. (People say Python comes with "batteries included" because of this.)
Once you've imported a module, you reach into it with a ., just like methods: math.sqrt(), math.pi.
Just the parts you need
If you only want one or two things from a module, you can grab them directly:
from math import sqrt, pi
print(sqrt(144))
print(pi)
Now you don't need the math. in front.
random
One of the most fun ones is random:
import random
print(random.randint(1, 6))
print(random.choice(["Karl", "Amer", "Zain", "Alex", "Rishabh"]))
random.randint(1, 6)gives back a random whole number from 1 to 6. (Both ends included this time, unlikerange!)random.choice(some_list)gives back one random thing from the list.
Run it a few times. You'll get something different almost every time.
Run this a few times!
Python exercise
Write the program in an editor next to the lesson, run it, and have it checked automatically. Create a free account to do this part.
Nobody wants to pay for the pizza. Let's let Python decide.
Make a function called who_pays that takes a list of names and returns one of them, picked at random.
Then print who's paying for crew, like this:
Rishabh is paying for the pizza!
(Your name will probably be different. That's the point!)
Python exercise
Write the program in an editor next to the lesson, run it, and have it checked automatically. Create a free account to do this part.
Do this lesson for real
With a free account you get the terminals, challenges and checks that go with the lessons in Intro to Python, and your progress is saved as you go. CyberAcad is a 501(c)(3) nonprofit, so there is nothing to pay.