笨方法”学Python3,习题 13:参数、解包和变量
1、 什么是脚本 ?
2、 如何将变量传递给脚本 ?
3、 什么是模块 ?
一、基础代码
所写的代码:
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:", second)
print("your third variable is:", third)
---------------------------------------------------------------------------------------------------
保存上述代码,在终端输入变量,应该看到的结果:
PS D:代码> & D:/软件/python/python.exe d:/代码/ex13.py first 2nd 3rd
The script is called: d:/代码/ex13.py
Your first variable is: first
Your second variable is: 2nd
your third variable is: 3rd
二、巩固练习
1、给少于3个参数
1、给0个参数,实际有1个参数,还缺少3个参数
PS D:代码> & D:/软件/python/python.exe d:/代码/ex13.py
Traceback (most recent call last):
File "d:/代码/ex13.py", line 3, in <module>
script, first, second, third = argv
ValueError: not enough values to unpack (expected 4, got 1)
2、给1个参数,实际有2个参数,还缺少2个参数
PS D:代码> & D:/软件/python/python.exe d:/代码/ex13.py first
Traceback (most recent call last):
File "d:/代码/ex13.py", line 3, in <module>
script, first, second, third = argv
ValueError: not enough values to unpack (expected 4, got 2)
3、给2个参数,实际有3个参数,还缺少1个参数
PS D:代码> & D:/软件/python/python.exe d:/代码/ex13.py first 2nd
Traceback (most recent call last):
File "d:/代码/ex13.py", line 3, in <module>
script, first, second, third = argv
ValueError: not enough values to unpack (expected 4, got 3)
2、更多的参数
所写的代码:
from sys import argv
script, name, age, height, weight = argv
print(f"The script is {script}.")
print("My name is {}.".format(name))
print("I'm", age, "old.")
print(f"I'm {height} cm",end = ", ")
print(f" {weight} kg.nI'm sure!!!t-u-")
---------------------------------------------------------------------------------------------------
应该看到的结果:
PS D:代码> & D:/软件/python/python.exe d:/代码/ps.py Jimmy 19 197 83
The script is d:/代码/ps.py.
My name is Jimmy.
I'm 19 old.
I'm 197 cm, 83 kg.
I'm sure!!! -u-
3、更少的参数&将input和argv一起使用
所写的代码:
from sys import argv
script, name, age = argv
height = input("What's your height ?")
weight = input("And weight ?")
print(f"The script is {script}.")
print("His name is {}.".format(name))
print("He is", age, "old.")
print(f"He is {height} cm",end = ", ")
print(f" {weight} kg.nI'm sure!!!t-u-")
----------------------------------------------------------------------------------------------------
应该看到的结果:
PS D:代码> & D:/软件/python/python.exe d:/代码/ps.py Jimmy 19
What's your height ?197
And weight ?83
The script is d:/代码/ps.py.
His name is Jimmy.
He is 19 old.
He is 197 cm, 83 kg.
I'm sure!!! -u-
总结:
1、脚本就是你编写的.py程序
2、可以通过input函数在终端输入变量来传递给脚本,也可以通过argv参数变量来传参
3、模块类似“库”,我们从库中引入特性
4、argv(argument variable)参数变量,可以同时定义多个变量,其中第一个为文件名
5、解包(unpack)是把argv中的东西取出,解包,将在终端(terminal)输入的所有参数依次赋值给左边的变量
^ v ^,知乎此系列文章内容均会在微信公众号中同步更新,公众号:小民有个小旮旯