python系统学习日记 L13 参数, 解包, 变量

本文记录了Python学习中关于参数、解包和变量的实践操作。通过修改代码并运行,展示了当传入参数数量不匹配时引发的`ValueError`。此外,还设计了接受不同数量参数的脚本,并结合`raw_input`获取用户输入,进一步理解参数处理和输入交互。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

书中代码:

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

修改代码为:

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)

输出结果:
python ex13.py 1 2 3
在这里插入图片描述
附加题:
1、给你的脚本三个以下的参数。看看会得到什么错误信息。试着解释一下?
在这里插入图片描述
ValueError: not enough values to unpack (expected 4, got 3)
规定的参数不足时,系统报参数不足的错误
2、再写两个脚本,其中一个接受更少的参数,另一个接受更多的参数,在参数解包时给它们取一些有意义的变量名。
2.1、两个参数的脚本

from sys import argv

script, height, weight = argv

print("The script is called:", script)
print("Your height is :", height)
print("Your weight is:", weight)

输出结果:

在这里插入图片描述
2.2 四个参数脚本

from sys import argv

script, position1, position2, position3, position4 = argv

print("left on the map maybe say:", position1)
print("up on the map maybe say:", position2)
print("right on the map say:", position3)
print("down on the may say:", position4)

输出结果:
python ex13.2.py west north east south
在这里插入图片描述
3、将 raw_input 和 argv 一起使用,让你的脚本从用户手上得到更多的输入。

from sys import argv

script, a1, a2 = argv

input_1 = input("Your " + a1 + " is: ")
input_2 = input("Your " + a2 + " is: ")

print("Your input %s is: %s " % (a1, input_1))
print("Your input %s is: %s " % (a2, input_2))

输出结果:
python ex13.3.py age weight
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值