学习python的第六天

提示别人

对于raw_input,还可以在括号里写入想要提示用户的字符串。如下所示:

Y = raw_input(“Name ?”)

括号中的Name?用来提示用户,然后将用户输入的结果赋值给变量Y

练习部分

age = raw_input("How old are you? ")
height = raw_input("How tall are you? ")
weight = raw_input("How much do you weigh? ")

print "So, you're %r old, %r tall and %r heavy." % (age, height, weight)
加分习题
1.在交互式界面下输入help(raw_input)的提示:
Help on built-in function raw_input in module __builtin__:

raw_input(...)
    raw_input([prompt]) -> string

    Read a string from standard input.  The trailing newline is stripped.
    If the user hits EOF (Unix: Ctl-D, Windows: Ctl-Z+Return), raise EOFError.
    On Unix, GNU readline is used if enabled.  The prompt string, if given, is printed without a trailing newline before reading.
2.

open: Open a file, returning an object of the file type described in section File Objects. If the file cannot be opened, IOError is raised. When opening a file, it’s preferable to use open() instead of invoking the file constructor directly.

file: Constructor function for the file type, described further in section File Objects. The constructor’s arguments are the same as those of the open() built-in function described below.

os: Miscellaneous operating system interfaces.

sys: System-specific parameters and functions.

参数、解包、变量

练习部分

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
  • 第一行的import语句的作用是将python的库(模组)引入你的脚本,用一个引用一个,既保证了程序的精简,而且在别的程序员看到的时候就很明了,知道你用了哪些库。
  • 第二行的argv是“参数变量”,是一个标准的编程术语,这个变量包包含了你传递给python的参数。
  • 第三行将argv解包(unpack),意思就是把argv中的东西解包,将所有的参数依次赋予左边的变量名。

但是如果这么写代码会报错:

Traceback (most recent call last):
  File "C:\Users\ex13.py", line 3, in <module>
    script, first, second, third = argv
ValueError: need more than 1 value to unpack

因为提供的参数个数不对,错误信息是告诉我参数数量不足。所以我把代码改成了如下样子:

from sys import argv

first = raw_input("FName: ")
second = raw_input("SName: ")
third = raw_input("TName: ")

script, first, second, third = argv, first, second, third

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

这样既保证了参数的数量完整,也可以从用户手上获取更多的输入。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值