Modules

decal·2023년 1월 12일
0

study notes

목록 보기
11/12

math module

import math

math.ceil()

  • method to round up to the nearest whole number

math.floor()

  • method to round the number down to the nearest whole number
import math    

print("Rounded up to the nearest number")
rounded = math.ceil(22.7324)
print(rounded)

Output:

Rounded up to the nearest number 23

We can find out the functionality a module has by using the help() instruction with the name of the module between the parentheses.

We can import the module created by a different developer.

import pygal

chart = pygal.Pie()
chart.title = "Favourite Type of Movie"
chart.add("Sci-Fi", 30)
chart.add("Romance", 25)
chart.add("Action", 45)


chart.render_in_browser()

statistics module

mean()

import statistics    

scores = [4, 4, 3, 6, 1, 2, 8, 4]
mean = statistics.mean(scores)
print(f"Mean score is {mean}")

Output:

Mean score is 4

We're able to use multiple different modules in the same file by adding a comma between the modules we're importing.

import statistics, math    

diameters = [9, 7, 4, 6]
result = statistics.mean(diameters)
print(f"Mean diameter is {result}")

print("Value of pi is:")
print(math.pi)

Output:

Mean diameter is 6.5 
Value of pi is: 
3.141592653589793

To just use a specific fuction from a module:

from math import pi    

print("Value of pi is:")
print(pi)

Output:

Value of pi is: 
3.141592653589793

When we use 'from', we don't need to add the name of the module anymore like the following:

from statistics import mean

test_scores = [33, 7, 4, 6]
result = mean(test_scores)
print(f"Mean result is {result}")

Output:

Mean result is 12.5

aliasing

  • using the keyword 'as' with a module
import math as m

print(m.floor(44.32))

Output:

44

0개의 댓글