The Python interpreter has a number of functions and types built into it that are always available.
This means that you don't have to import anything so that you can access them.
Some of the built-in functions are so powerful, simple, common or useful, such as print() that it's difficult to imagine
a block of code without them.
As we have advanced through this course, we've seen and used many built-in functions (bin(), chr(), complex(), dict(), format(), hex(), input()) perhaps without realizing that
they have their own place and classification in the Python documentation.
In the python documentation the range() type is included under "Built-in Functions."
However, range() is actually an immutable sequence type similar to lists and tuples.
Conceptually range() is similar to a tuple containing a well-defined sequence of values.
Both the sequence and the values may be huge, but range() occupies only a small amount of memory
and it is very fast.
Of the three arguments stop must be included. If start
is not included, it defaults to If step
is not included, it defaults to
>>>list(range(4))[0,1,2,3]# 'stop' is not included in the range.>>>>>>list(range(4,9))[4,5,6,7,8]>>>>>>list(range(4,37,7))[4,11,18,25,32]>>>>>>tuple(range(3,-7,-2))(3,1,-1,-3,-5)>>>>>>tuple(range(3,-7,0))Traceback(mostrecentcalllast):File"<stdin>",line1,in<module>ValueError:range()arg3mustnotbezero>>>>>>tuple(range(3,-7,4))()# Empty range.>>>
>>>100_000_000_000_000inrange(-5_123_456_789,1_000_000_000_000_000,7)False>>>100_000_000_000_001inrange(-5_123_456_789,1_000_000_000_000_000,7)False>>>100_000_000_000_002inrange(-5_123_456_789,1_000_000_000_000_000,7)True>>>>>>len(range(-5_123_456_789,1_000_000_000_000_000_456_789_123,789_012_456))1267407114292763>>>>>>len(range(5_123_456_789,-1_000_000_000_000_000_456_789_123,-789_012_456))1267407114292763>>>>>>a,b,c=5_123_456_789,-1_000_000_000_000_000_456_789_123,-789_012_456>>>d,e,f=407114292763,267407114292763,674071142>>>range(a,b,c)[d:e:f]range(-321218248000514199139,-210987544000000514199139,-531850527268144752)>>>len(range(a,b,c)[d:e:f])396_101>>>range(a,b,c)[d:e:f][763::2345][-3]-207760474949976816255955>>>>>># and it's very fast.
This expression has the appearance of a function but it returns and behaves like a dictionary representing the current global symbol table.
Invoke python on Unix and display information about globals():
$python3.6Python3.6.3(v3.6.3:2c5fed86e0,Oct32017,00:32:08)[GCC4.2.1(AppleInc.build5666)(dot3)]ondarwinType"help","copyright","credits"or"license"formoreinformation.>>>>>>type(globals())<class'dict'>>>>>>>globals(){'__name__':'__main__','__doc__':None,'__package__':None,'__loader__':<class'_frozen_importlib.BuiltinImporter'>, '__spec__':None,'__annotations__':{},'__builtins__':<module'builtins'(built-in)>}# Braces '{}' enclose a dictionary.# Each key '__name__', '__doc__', '__package__' .... is a string.# Each value '__main__', None, None, .... may or may not be a string. Most values above are not strings.>>>quit()$
When you invoke python interactively, the above global variables are predefined. Unless you really know what you are doing,
it is recommended that you do not attempt to change any of the predefined global variables.
>>>v1=6;t1=(1,2,3)>>>globals(){'__name__':'__main__','__doc__':None,'__package__':None,'__loader__':<class'_frozen_importlib.BuiltinImporter'>, '__spec__':None,'__annotations__':{},'__builtins__':<module'builtins'(built-in)>,'v1':6,'t1':(1,2,3)}>>>>>>v1inglobals()False>>>'v1'inglobals()# Each key is a string.True>>>'v2'inglobals()# Use this feature to determine whether or not global variable v2 exists.False>>>>>>s1='v1'>>>globals(){# 7 predefined global variables as above.'v1':6,'t1':(1,2,3),'s1':'v1'}>>>s1inglobals()True>>>globals()[s1]6>>>'s1'inglobals()True>>>globals()['s1']'v1'>>>
Change syntax of import statement slightly and try again:
>>>fromdecimalimport*>>>>>>globals()'__name__''__main__''__doc__'None'__package__'None'__loader__'<class'_frozen_importlib.BuiltinImporter'>'__spec__'None'__annotations__'{}'__builtins__'<module'builtins'(built-in)>'getcontext'<built-infunctiongetcontext>'setcontext'<built-infunctionsetcontext>'localcontext'<built-infunctionlocalcontext>'Decimal'<class'decimal.Decimal'>'Context'<class'decimal.Context'>'DecimalTuple'<class'decimal.DecimalTuple'>'DecimalException'<class'decimal.DecimalException'>'Clamped'<class'decimal.Clamped'>'Rounded'<class'decimal.Rounded'>'Inexact'<class'decimal.Inexact'>'Subnormal'<class'decimal.Subnormal'>'Underflow'<class'decimal.Underflow'>'Overflow'<class'decimal.Overflow'>'DivisionByZero'<class'decimal.DivisionByZero'>'FloatOperation'<class'decimal.FloatOperation'>'InvalidOperation'<class'decimal.InvalidOperation'>'ConversionSyntax'<class'decimal.ConversionSyntax'>'DivisionImpossible'<class'decimal.DivisionImpossible'>'DivisionUndefined'<class'decimal.DivisionUndefined'>'InvalidContext'<class'decimal.InvalidContext'>'DefaultContext'Context(prec=28,rounding=ROUND_HALF_EVEN,Emin=-999999,Emax=999999,capitals=1,clamp=0,flags=[],traps=[InvalidOperation,DivisionByZero,Overflow])'HAVE_THREADS'True'BasicContext'Context(prec=9,rounding=ROUND_HALF_UP,Emin=-999999,Emax=999999,capitals=1,clamp=0,flags=[],traps=[Clamped,InvalidOperation,DivisionByZero,Overflow,Underflow])'ExtendedContext'Context(prec=9,rounding=ROUND_HALF_EVEN,Emin=-999999,Emax=999999,capitals=1,clamp=0,flags=[],traps=[])'MAX_PREC'999999999999999999'MAX_EMAX'999999999999999999'MIN_EMIN'-999999999999999999'MIN_ETINY'-1999999999999999997'ROUND_UP''ROUND_UP''ROUND_DOWN''ROUND_DOWN''ROUND_CEILING''ROUND_CEILING''ROUND_FLOOR''ROUND_FLOOR''ROUND_HALF_UP''ROUND_HALF_UP''ROUND_HALF_DOWN''ROUND_HALF_DOWN''ROUND_HALF_EVEN''ROUND_HALF_EVEN''ROUND_05UP''ROUND_05UP'>>>>>>d1=Decimal(6);d1# With this syntax class Decimal is defined as global variable.Decimal('6')>>>>>>type(globals()['MIN_ETINY'])<class'int'>>>>type(globals()['DefaultContext'])<class'decimal.Context'>>>>type(globals()['DivisionByZero'])<class'type'>>>>>>>type(globals()['ROUND_HALF_UP'])<class'str'>>>>globals()['ROUND_HALF_UP']=='ROUND_HALF_UP'# In this case key and value are the same.True>>>
globals() may be used for communication between nested functions. In the code below, function2() is defined within function1()
and function3() is defined within function2().
By means of globals(),function3() can access the local variables of both function1() and function2():
This expression has the appearance of a function but it returns and behaves like a dictionary representing the current local symbol table.
At module level, globals and locals are the same dictionary. This means that,
outside the body of a function, globals() and locals() are the same. Within the body of a function
locals() assumes its individual identity.
1.globals()={# Predefined globals.'function1':<functionfunction1at0x100561e18>}1.locals()={}# A change in locals() does not appear in globals():2.globals()={# Predefined globals.'function1':<functionfunction1at0x100561e18>}2.locals()={'t1':(1,2,3)}# A change in globals() does not appear in locals():3.globals()={# Predefined globals.'function1':<functionfunction1at0x100561e18>,'v1':1.5}3.locals()={'t1':(1,2,3)}# Outside function1() globals() and locals() are the same, and globals() keeps the value 'v1':4.globals()={# Predefined globals.'function1':<functionfunction1at0x100561e18>,'v1':1.5}4.locals()={# Predefined globals.'function1':<functionfunction1at0x100561e18>,'v1':1.5}
In your python code experiment with statements like import sys, from sys import * and the same for subprocess or re instead of sys. Use globals() so that you can see exactly what you have imported.