Python terminology: things to left of “= argv” in Learn Python the Hard Way exercise 13

狂风中的少年 提交于 2019-11-29 11:51:27
Levon

The things to the left of the "=" are variables that get their value from the variable on the right.

Given:

script, first, second, third = argv

argv is a list of strings which in this case contains 4 items. These strings are "unpacked" and assigned to the four variables on the left of the =.

argv gets its value is when a Python program is invoked from the command line, like this:

test.py this is sure cool

in this case argv will contain ['test.py', 'this', 'is', 'sure', 'cool']. These strings after the command are called "command line arguments" (see this tutorial) and the name of the script, and any arguments are stored in argv. This is a way to send information to the script when you start it.

In this case the variables get the following values:

  script is set to  "this.py"  # the string is in argv[0]
  first to "is"     # argv[1]
  second to "sure"  # argv[2]

and

  third to "cool"   # argv[3]

So:

  script, first, second, third = argv

is really equivalent to:

  script = argv[0]
  first = argv[1]
  second = argv[2]
  third = argv[3]

It's only that Python lets you do this assignment in one nice swoop.

Note that you can pull out your command line arguments in any order using the appropriate index value.

This mechanism is used to communicate information the to the Python script. You can imagine running a program that expects an input file and and output file. Instead of hardcoding them in your script, you could provide them on the command line. E.g.,

 computeData.py input.txt result.txt

Sometimes it's easier to just type some code into the interactive python prompt, and see how these things work.

While sys.argv is a list that is defined for you by Python itself, it's not that different from any list or tuple (the mutable and non-mutable array-like types of Python) you define yourself. So try defining one yourself and play with it. After you've declared a variable named argv = ['123','456','789'] that is a list type, try assigning it to another name:

  anothername = argv

Note that nothing special happens. now notice what happens if you instead try to assign to three different variables:

  v1,v2,v3 = argv

The first (technically, "zeroeth") element in argv is stored in v1, the second element of argv is stored in v2, and so on.

I believe I would call v1,v2,v3 a "list of variables that are going to hold stuff that used to be elements in the list argv, but which I wish to unpack and store in their own place".

To answer your first question, argv is an attribute of the sys module. As for your second question, Python's docs do not specify a name for the right-hand side of assignment expressions, but script, first, etc. can be called variables in this context.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!