zoukankan      html  css  js  c++  java
  • 练习13--参数,解包,变量

    一 基本语法

    本次习题的主要内容是学习如何编写一个可以接收多个命令行参数的脚本程序,其中涉及到三个新的知识点是:如何导入一个模块、参数是什么以及解包的概念

    1 导入:其目的是将python的库/模块/功能(暂时这么写吧,概念不一样)导入到我们的脚本程序中,使得脚本程序可以直接使用python中的一些内容,具体格式是:from sys import argv,其中sys应该是相应的库,argv是一个我们想要导入的变量

    2 参数:我们在运行python脚本程序的时候会输入一行命令:python  ex13.py ,其中ex13.py就是一个参数

    3 解包:程序中有一行代码:script,first,second,third = argv,它的作用是:“把 argv 中的东西解包,将所有的参数依次赋予左边的变量名,即把它分成了四个变量: script ,first , second , 以及 third”。

    4 程序代码:

    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)
    print(argv)

    二 程序的运行和一些拓展内容

    1 如何运行程序:因为我们在程序中将变量argv解包成四个变量了,所以在命令行运行程序的时候,如果仍旧使用命令python  ex13.py ,则系统会报错,因为我们的脚本程序实际上需要四个参数,而我们只传递了一个参数,正确的命令是:python ex13.py first 2nd 3ndd。下面是我自己测试的一些不同命令的执行结果:

    • 命令python  ex13.py 的执行结果:
    •  命令python ex13.py first 2nd 3ndd的执行结果:
    •  命令 python ex13.py first 2nd 3ndd  stuff的执行结果:
    • 命令python stuff first 2nd 3nd的执行结果:
    • 命令python ex13.py stuff things thar的执行结果:

    以上结果说名:第一个参数必须是我们要执行的脚本文件的文件名,其它三个参数的内容可以任意定,但参数的个数不能多也不能少,必须是四个,否则都会报错。

    2 程序的拓展

    主要方法是把input()函数跟argv结合起来,重新创建一个脚本程序,我的代码如下:

    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)
    print(argv)
    first = int(input("请输入一个新的first值:"))
    print("新的first变量的值为:",first)
    print(argv)
    age = int(input("How old are you:"))
    print(f"Your age is:{age}")
    print("Your age is:",age)

    执行结果: 

         

    上面的执行结果说明代码:first = int(input("请输入一个新的first值:")) 中的first被重新指给了另外一个数据“15”,而argv里面的数据stuff并没有因为first的变化而改变,说明了python语言中变量定义的一个显著特征:它不是把值存储在变量中,更像是把名字(变量)贴在值上面

    3  argv 和和 input() 之间的区别是什么?区别取决于用户在哪被要求输入,如果是在命令行,就用 argv。如果你想让它们在程序已经运行的情况下用键盘输入,那就用 input() 。

    4  命令行参数是字符串吗? 是的,它们是以字符串的形式进来的,即使你在命令行输入的是数字。你可以用 int() 把它们转化成数值,就像 int(input()) 。

    三 我的问题

    1 能不能在脚本中更改argv变量里面的值?如果可以的话怎么改?代码怎么写?


     

  • 相关阅读:
    Indy10 系列(一)——获取最新的Indy源码
    Oracle9i中关于select into的执行过程 (转)
    Oracle创建删除用户、角色、表空间、导入导出数据库命令行方式总结(转)
    手动创建Oracle 11g数据库(转载)
    Indy10 系列(四)——编译Indy源码
    Indy10 系列(二)——获取最新的Indy源码
    Delphi 2010手动安装indy10.5.7
    Indy10 系列(三)——获取最新的Indy源码
    Indy10 系列(五)——安装Indy控件,重新编译Lazarus
    Unix文化RTFM
  • 原文地址:https://www.cnblogs.com/luoxun/p/13197074.html
Copyright © 2011-2022 走看看