习题13:参数,解包,变量

发布时间:2017-11-09 14:43:52编辑:Run阅读(3446)

    练习下面的程序,后面将看到详细解释

    代码如下

    # coding: utf-8
    __author__ = 'www.py3study.com'
    from sys import argv
    script, first, second, third = argv
    print("The script is called:", script)
    print("Your first variable is:", first)
    print("Your second variable is:", second)
    print("Your third variable is:", third)

    先别急着运行程序,分析下代码先

    在第三行,有一个"import"语句,这是你将python的功能引入你的脚本方法,python不会一下子将所有的功能都给你,而是让你需要什么就调用什么,这样可以让你的程序保持精简,而后面的程序员看到你的代码,这些"import"可以作为提示,让它们明白你的代码用到了哪些功能

    argv 是所谓的"参数变量",是一个非常标准的编程术语,在其它的编程语言里你也可以看到它,这个变量包含了你传递给python的参数

    第4行将argv"解包(unpack)",与其将所有参数放到同一个变量下面,我们将每个参数赋予一个变量名: script,first,second以及third. 这也许看上去有些奇怪,不过“解包”可能是最好的描述方式了。它的含义很简单:“把argv中的东西解包,将所有的参数依次赋予左边的变量名”,接下来就是正常的打印了。

    前面使用import让你的程序实现更多的功能,但实际上没人把import称为“功能”,真正的名称叫:模组(modules)


    应该看到的结果(注意必须传递3个参数)

    python lianxi_13.py first 2nd 3nd

    E:\test>python lianxi_13.py first 2nd 3nd
    The script is called: lianxi_13.py
    Your first variable is: first
    Your second variable is: 2nd
    Your third variable is: 3nd

    其实可以将"first","2nd","3nd"替换成任意三样东西

    E:\test>python lianxi_13.py one two three
    The script is called: lianxi_13.py
    Your first variable is: one
    Your second variable is: two
    Your third variable is: three


    当运行脚本时提供的参数个数不对的时候,程序会报错,你将会看到以下信息:

    E:\test>python lianxi_13.py first 2nd
    Traceback (most recent call last):
      File "lianxi_13.py", line 4, in <module>
        script, first, second, third = argv
    ValueError: not enough values to unpack (expected 4, got 3)

    not enough values to unpack (expected 4, got 3)这个错误信息告诉你参数数量不足





关键字