#!/usr/bin/env python # coding: utf-8 # # Modules # - module is a file containing Python definitions and statements intended for use in other Python programs # - many Python modules come with built-in standard library # ## Various ways to import names into the current namespace # In[ ]: # import math module into the global namespace import math x = math.sqrt(100) print(x) # In[ ]: import random print(random.choice(list(range(1, 21)))) # In[ ]: from random import choice # In[ ]: print(choice([1, 2, 3, 4])) # In[ ]: help(math) # In[ ]: from math import * # Import all the identifiers from math print(sqrt(100)) print(pi) # In[ ]: from math import radians, sin rad = radians(90) print(rad) print(sin(rad)) # ## names can be imported to local namespace # In[ ]: def isUpper(letter): import string # string name is local return letter in string.ascii_uppercase # In[15]: print(isUpper('a')) # In[2]: # can we use string module outside isUpper function? print(string.digits) # ## scope and lookup rules #
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 available #Precedence rule:
#