exercise 13

# 这是将Python的功能模块加入你自己脚本的方法
from sys import argv
# read the wyss section for how to run this
# 将 argv进行“解包(unpack)”
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)

注意:

一定要用命令行,通过$ python ex13.py first 2nd 3rd命令运行程序

练习

  1. Try giving fewer than three arguments to your script. See that error you get? See if you can explainit.
  2. Write a script that has fewer arguments and one that has more. Make sure you give the unpackedvariables good names.
  3. Combine input with argv to make a script that gets more input from a user. Don’t overthink it. Justuse argv to get something, and input to get something else from the user.
  4. Remember that modules give you features. Modules. Modules. Remember this because we’ll needit later.

答案

  1. 输入命令:python ex13.py first 2nd会出现以下错误:
Traceback (most recent call last):
  File "ex13.py", line 3, in <module>
    script, first, second, third = argv
ValueError: not enough values to unpack (expected 4, got 3)

输入命令:python ex13.py first 2nd 3rd 4th会出现以下错误:

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

所以输入命令要根据变量的个数决定,太多太少都不行。

代码1:

from sys import argv
apple, banana, orange, pear, pineapple = argv

print("The first fruit is called", apple)
print("The sceond furit is called", banana)
print("The third fruit is called", orange)
print("The fourth furit is called", pear)
print("The fifth fruit is called", pineapple)

代码2:

from sys import argv
bear, wolf, tigger = argv

print("the bear is",bear)
print("the wolf is",wolf)
print("the tigger is",tigger)

代码:

from sys import argv
dog, cat = argv

print("the dog is called",dog)
print("the cat is called",cat)

fish = input("input name:")
print(f"the fish is called {fish}")

题目中讲了不要多虑,应该就是分开使用吧。

小结:参数, 解包, 变量
·from sys import argv·是导入模块的作用,这个模块具体的作用应该是把在命令行输入的参数打包,再在script,first,second,third = argv中解包,分配给各个变量。命令行输入的第一个参数一定是文件名称。

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容