提示别人
对于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
这样既保证了参数的数量完整,也可以从用户手上获取更多的输入。