《“笨办法”学python3》Ex 13

知识点:

from sys import argv

import可以将python特性(模块module)引入脚本,需要什么调用什么,使得代码很小. import 也可以作为文档查

script,first,second,third = argv

argv是参数变量,这行代码将argv解包.将(命令行中的)输入参数赋给4个变量

写一个接受参数的脚本. 

按照程序输入,出现报错:not enough values to unpack (expected 4, got 1)

原因在于没有添加命令行参数

由于设定的参数是4个,因此包括文件名应该有4个参数,否则报错

argv 与 input( ) 区别?

argv在命令行中输入,input在脚本中输入. 

程序:

from sys import argv
# read the WYSS section for how to run this
script,first,second,third = argv

print("The script is called:", script)
print("Your first variable is:", first)
print("Your second variable is:", third)

输出:

PS C:\Users\xue weiruan\github> python ex13.py 1 2 3
The script is called: ex13.py
Your first variable is: 1
Your second variable is: 3
PS C:\Users\xue weiruan\github> python ex13.py my name xp
The script is called: ex13.py
Your first variable is: my
Your second variable is: xp
PS C:\Users\xue weiruan\github> python ex13.py my name
Traceback (most recent call last):
  File "ex13.py", line 3, in 
    script,first,second,third = argv
ValueError: not enough values to unpack (expected 4, got 3)
PS C:\Users\xue weiruan\github> python ex13.py my name xp xpp
Traceback (most recent call last):
  File "ex13.py", line 3, in 
    script,first,second,third = argv
ValueError: too many values to unpack (expected 4)
PS C:\Users\xue weiruan\github>

 

你可能感兴趣的:(Python)