- Python Basics
- Collections
- Control Flow
- Functions
- Classes
- Modules
- Generators and Decorators
- Python Next
Example code based on
LearnXinYminutes
and licensed under
CC Attribution-Share 3
Modules
Collapse Content
Show Content
# You can import modules
import math
print(math.sqrt(16) )#=> 4
# You can get specific functions from a module
from math import ceil, floor
print(ceil(3.7)) #=> 4.0
print(floor(3.7)) #=> 3.0
# You can import all functions from a module.
# Warning: this is not recommended
from math import *
# You can shorten module names
import math as m
math.sqrt(16) == m.sqrt(16) #=> True
# `dir` lists all the functions and attributes defined by a module
import math
dir(math)
# => [... 'acos', 'acosh', 'asin', 'asinh', 'atan'] #and more...
Create your own modules
Python modules are just ordinary python files. You can write your own, and import them. The name of the module is the same as the name of the file.
greetings.py
file:
def say_hi():
print("Hi")
def say_bye():
print("Bye")
Console:
import greetings
greetings.say_hi() # => Hi
greetings.say_bye() # => Bye
Challenge
You typed the following code: import math as m
. What code can you now type to get the factorial of x
?
Please sign in or sign up to submit answers.
Alternatively, you can try out Learneroo before signing up.