http://openbookproject.net/thinkcs/python/english3e/modules.html
# import math module into the global namespace
import math
x = math.sqrt(100)
print(x)
import random
print(random.choice(list(range(1, 21))))
from random import choice
print(choice([1, 2, 3, 4]))
help(math)
from math import * # Import all the identifiers from math
print(sqrt(100))
print(pi)
from math import radians, sin
rad = radians(90)
print(rad)
print(sin(rad))
def isUpper(letter):
import string # string name is local
return letter in string.ascii_uppercase
print(isUpper('a'))
False
# can we use string module outside isUpper function?
print(string.digits)
--------------------------------------------------------------------------- NameError Traceback (most recent call last) <ipython-input-2-1f51304bf154> in <module>() 1 # can we use string module outside isUpper function? ----> 2 print(string.digits) NameError: name 'string' is not defined
The scope of an identifier is the region of program code in which the identifier can be accessed, or used.
Three important scopes in Python: - Local scope refers to identifiers declared within a function - Global scope refers to all the identifiers declared within the current module, or file - Built-in scope refers to all the identifiers built into Python -- those like range and min that are (almost) always availablePrecedence rule:
def testLocalScope():
k = 5
for i in range(2):
for j in range(2):
if i == j:
k = 3
print('inside=',k)
print('outside=',k)
test()
inside= 3 inside= 3 outside= 3
print(k)
--------------------------------------------------------------------------- NameError Traceback (most recent call last) <ipython-input-21-eb2fa875d160> in <module>() ----> 1 print(k) NameError: name 'k' is not defined
import fibos
help(fibos)
Help on package fibos: NAME fibos PACKAGE CONTENTS fibo FILE /Volumes/Storage/CMU/Sp2019/CS0/thinkpythonnotebooks/fibos/__init__.py
fibos.fibo.fib(10)
--------------------------------------------------------------------------- AttributeError Traceback (most recent call last) <ipython-input-5-94afb397843e> in <module>() ----> 1 fibos.fibo.fib(10) AttributeError: module 'fibos' has no attribute 'fibo'
import fibos.fibo as f
f.fib(10)
0 1 1 2 3 5 8 13 21 34
from fibos import fibo
fibo.fib(10)
0 1 1 2 3 5 8 13 21 34