1. python输入raw_input()函数。
a = raw_input() #得到的是字符串 a = int(raw_input()) #如果想得到int,只能这样
如果输入特殊字符,比如\t \n等,会和输入一样输出,%r会输出\\t、\\n,%s会输出\t、\n
View Code
print "How old are you?" age = raw_input() print "How tall are you?" height = raw_input() print "How much do you weight?" weight = raw_input() print "So, you are %r old, %r tall and %r heavy." % (age, height, weight) print "So, you are %s old, %s tall and %s heavy." % (age, height, weight) print "So, you are %d old, %d tall and %d heavy." % (int(age), int(height), int(weight))
输出
View Code
How old are you? \t How tall are you? \n How much do you weight? 111 So, you are '\\t' old, '\\n' tall and '111' heavy. So, you are \t old, \n tall and 111 heavy.
通常都是这么写的
View Code
age = raw_input("How old are you?") height = raw_input("How tall are you?") weight = raw_input("How much are you weight?") print "So, you're %r old, %r tall and %r heavy." % (age, height, weight)
input和raw_input的区别
当输入为纯数字时
-
input返回的是数值类型,如int,float
-
raw_inpout返回的是字符串类型,string类型
输入字符串为表达式
input会计算在字符串中的数字表达式,而raw_input不会。
如输入 “57 + 3”:
-
-
input会得到整数60
-
raw_input会得到字符串”57 + 3”
-
其实
def input(prompt): return (eval(raw_input(prompt)))
2. 在windows中查看doc,可以用如下命令
python -m pydoc raw_input
3. 运行python脚本的时候输入参数,该如何写。
看代码
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
argv类似于java中的main(String[] args)。但是argv需要指定参数个数,并且运行脚本的时候参数个数要对应,不然会报错。并且第一个参数是python ex13.py 1 1 1中的ex13.py。
如果参数个数不对,输出如下:
View Code
E:\SkyDrive\python\the hard way to learn python>python ex13.py 1 2 3 4 Traceback (most recent call last): File "ex13.py", line 2, in <module> script, first, second, third = argv ValueError: too many values to unpack
4. 读取文件并打印
在脚本中读取文件,最好把文件名作为脚本的参数,以下是代码
from sys import argv script, filename = argv txt = open(filename) print txt.read()
txt.close() file_name_again = raw_input("the filename you want to print \n > ") print open(file_name_again).read()
输出
View Code
E:\SkyDrive\python\the hard way to learn python>python ex15.py ex15_sample.txt This is stuff I typed into a file. It is really cool stuff. Lots and lots of fun to have in here. the filename you want to print > ex15_sample.txt This is stuff I typed into a file. It is really cool stuff. Lots and lots of fun to have in here.