Skip to content

Instantly share code, notes, and snippets.

@krazylearner
Created June 17, 2015 11:13
Show Gist options
  • Select an option

  • Save krazylearner/9c6ac54e695ba0fe6904 to your computer and use it in GitHub Desktop.

Select an option

Save krazylearner/9c6ac54e695ba0fe6904 to your computer and use it in GitHub Desktop.
#As your program gets longer, you may want to split it into several files for easier maintenance.
#You may also want to use a handy function that you’ve written in several programs without copying its definition into each program.
#To support this, Python has a way to put definitions in a file and use them in a script or in an interactive instance of the interpreter.
#Such a file is called a module; definitions from a module can be imported into other modules or into the main module
# Fibonacci numbers module
# fibo.py
def fib(n): # write Fibonacci series up to n
a, b = 0, 1
while b < n:
print b,
a, b = b, a+b
def fib2(n): # return Fibonacci series up to n
result = []
a, b = 0, 1
while b < n:
result.append(b)
a, b = b, a+b
return result
#import this module with the following command:
import fibo
Using the module name you can access the functions:
>>> fibo.fib(1000)
1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987
>>> fibo.fib2(100)
[1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
>>> fibo.__name__
# If you intend to use a function often you can assign it to a local name:
>>> fib = fibo.fib
>>> fib(500)
1 1 2 3 5 8 13 21 34 55 89 144 233 377
#There is a variant of the import statement that imports names from a module directly into the importing module’s symbol table.
#For example:
>>> from fibo import fib, fib2
>>> fib(500)
1 1 2 3 5 8 13 21 34 55 89 144 233 377
# There is even a variant to import all names that a module defines:
>>> from fibo import *
>>> fib(500)
1 1 2 3 5 8 13 21 34 55 89 144 233 377
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment