Importing Libraries
Part of the Data and Plots section of Coddy's Machine Learning journey. Lesson 3 of 60.
Python's own functions stop at basics like len and round. For more, you import a module: ready-made code. Machine learning stands on NumPy:
import numpy as np
print(np.sqrt(49)) # a function: parentheses
print(np.pi) # a value: no parentheses
print(np.round(2 * np.pi * 3, 2)) # round to 2 decimalsThis prints:
7.0
3.141592653589793
18.85as np gives NumPy a short nickname, an alias. A dot reaches inside it. Note that np.sqrt always answers with a decimal: 7.0, not 7.
Import once, at the top, and every line below can use np.
Challenge
EasyA pizzeria wants a square pizza as big as its round one. The program reads the round pizza's diameter in centimeters.
- Import NumPy as
np. - Find the area:
np.pitimes the radius squared. The radius is half the diameter. - Find the square's side: the square root of the area.
- Print both, rounded to 2 decimals with
np.round.
For a 40 cm pizza, the two shapes look like this:
and the program prints:
Area: 1256.64
Side: 35.45Try it yourself
# Import NumPy on the line below
diameter = float(input())
# Write your code below
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Data and Plots
2NumPy Arrays
Creating ArraysShape and SizeRanges of NumbersIndexing and SlicingRecap: Temperature GridPractice on your own: Online Python compiler