1, in the module, we need to determine whether __name__ is assigned to "__main__".
python <arguments>
2. In the case of script execution, the __name__ attribute of the module will be assigned to __main__, and that's why.
$ python 50 0 1 1 2 3 5 8 13 21 34
3. If imported as a module, it will not be executed:
>>> import fibo >>>
Knowledge Point Expansion:
Python Dynamic Declaration Variable Assignment Code Example
Through exec(), globals() and locals()
# By exec() for i in range(1, 4): # The first time you loop i=1, you execute the python statement ex1 = "exec1" in the string, and so on. exec(f'ex{i} = "exec{i}"') # By globals() and locals() def test(): # globals() for i in range(1, 4): # At first loop i=1, execute globals()['gb1'] = 'global1', globals() is a dict globals()[f'gb{i}'] = f'global{i}' # locals() for i in range(1, 4): locals()[f'lc{i}'] = f'local{i}' # Trying to print locals' variables try: print(lc1, lc2, lc3) # It's gonna be wrong except Exception as e: print(e) print(locals()['lc1'], locals()['lc2'], locals()['lc3']) # By key-value pairs if __name__ == '__main__': # Execution test() print('---------------------') # Print function-defined global variables print(gb1, gb2, gb3) print('---------------------') # Print variables defined via exec() print(ex1, ex2, ex3)
Output.
name 'lc1' is not defined local1 local2 local3 --------------------- global1 global2 global3 --------------------- exec1 exec2 exec3
This article on the python module to determine the assignment of global variables to explain the example of the article is introduced to this, more related to python to determine the assignment of global variables, please search for my previous posts or continue to browse the following related articles I hope you will support me in the future more!