官术网_书友最值得收藏!

How to do it...

To illustrate scope, we will create nested functions, where a function is defined and then called within an enclosing function:

  1. nested_functions.py includes a nested function, and ends with calling the nested function:
      >>> def first_funct():
... x = 1
... print(x)
... def second_funct():
... x = 2
... print(x)
... second_funct()
...
  1. First, call the parent function and checks the results:
      >>> first_funct()
1
2
  1. Next, call the nested function directly and notice that an error is received:
      >>> second_funct()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'second_funct' is not defined
  1. To work with another module, import the desired module:
      >>> import math
  1. Below, we call the sin() function from within the module in the form <module>.<function>:
      >>> math.sin(45)
0.8509035245341184
  1. Try calling a function, as demonstrated below, without using the dot-nomenclature to specify its library package results in an error:
      >>> sin(45)
      Traceback (most recent call last):
        File "<stdin>", line 1, in <module>
       NameError: name 'sin' is not defined
  1. Alternatively, the example below shows how to import all items from a module using the * wildcard to place the items within the current program's namespace:
      >>> from math import *
      >>> sin(45)
      0.8509035245341184
  1. A common way to run modules as scripts is to simply call the module explicitly from the command line, providing any arguments as necessary. This can be set up by configuring the module to accept command-line arguments, as shown in print_funct.py:
        def print_funct(arg):
            print(arg)
            if __name__ == "__main__":
                import sys
                print_funct(sys.argv[1])
  1. print_mult_args.py shows that, if more than one argument is expected, and the quantity is known, each one can be specified using its respective index values in the arguments list:
        def print_funct(arg1, arg2, arg3):
            print(arg1, arg2, arg3)
        if __name__ == "__main__":
            import sys
            print_funct(sys.argv[1], sys.argv[2], sys.argv[3])
  1. Alternatively, where the function can capture multiple arguments but the quantity is unknown, the *args parameter can be used, as shown below:
      >>> def print_input(*args):
      ...   for val, input in enumerate(args):
      ...       print("{}. {}".format(val, input))
      ...
      >>> print_input("spam", "spam", "eggs", "spam")
      0. spam
      1. spam
      2. eggs
      3. spam
主站蜘蛛池模板: 赤峰市| 漳浦县| 民勤县| 长葛市| 凤山县| 古浪县| 文山县| 冕宁县| 顺平县| 五常市| 达日县| 菏泽市| 门头沟区| 孟连| 滨州市| 洛扎县| 盐城市| 剑河县| 扎赉特旗| 福贡县| 文水县| 奇台县| 土默特左旗| 南康市| 新疆| 澄迈县| 广南县| 安溪县| 高青县| 鄂尔多斯市| 香港 | 兴安盟| 安溪县| 焦作市| 禄丰县| 兴山县| 金坛市| 大渡口区| 西充县| 敦煌市| 海城市|