第二篇、习题11至习题20
习题11、关于raw_input()引入
代码段:
print "How old are you?",
age = raw_input()
print "How tall you are?",
height = raw_input()
print "How much do you weight?",
weight = raw_input()
print "So you're %r old, %r tall and %r heavy."%(age, height, weight)
"
结果:
不同输入下的输出:
How old are you? 24
How tall you are? 180
How much do you weight? 75
So you’re ‘24’ old, ‘180’ tall and ‘75’ heavy.How old are you? 24years
How tall you are? 180cm
How much do you weight? 70kg
So you’re ‘24years’ old, ‘180cm’ tall and ‘70kg’ heavy.
注意:
1、raw_input()输入为字符串,其内部包含了打印功能,上面可以改为age = raw_input(“How old are you?”)同样效果
2、可强制类型转换,将字符串转换为int 即:age = int(raw_input(“How old are you?”))
习题12、raw_input()提示
代码段:
age = raw_input("How old are you ?")
height = raw_input("How tall you are?")
weight = raw_input("How weight you are?")
print "So you're %r old, %r tall and %r heavy."%(age, height, weight)
结果:
与习题11完全一致
注意:
1、raw_input()可以让它显示一个提示,从而告别别人应该输入什么东西,可以在()之间放入一个你想要作为提示的字符串
补充内容:
1、Terminal终端输入:pydoc raw_input
输出:
Help on built-in function raw_input in module builtin:
raw_input(…)
raw_input([prompt]) -> stringRead 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.
关于pydoc:是Python的文档工具
习题13、参数、解包和变量
代码段:
from sys import argv #sys是模块
#argv是“参数变量”(argument variable),这个变量保存着运行Python脚本时传递给Python脚本的参数
#这一行将argv“解包”(unpack),将argv中的东西解包
#将所有参数依次赋值给左边的变量,script、first、second和Third.
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
结果:
不同输入下的输出:
root@db1:~/share/python/Hardway# python second.py 1 2 3 4
Traceback (most recent call last):
File “second.py”, line 64, in
script, first, second, third = argv
ValueError: too many values to unpack
当给予三个以上的参数,提示在解包时值过多,运行脚本时参数的个数不匹配root@db1:~/share/python/Hardway# python second.py a b
Traceback (most recent call last):
File “second.py”, line 64, in
script, first, second, third = argv
ValueError: need more than 3 values to unpack
当给予三个以下的参数,提示在解包时输入值过少,运行脚本时参数个数不匹配root@db1:~/share/python/Hardway# python second.py 1 2 3
The script is called: second.py
Your first variable is: 1
Your second variable is: 2
your third variable is: 3root@db1:~/share/python/Hardway# python second.py first 2nd 3rd
The script is called: second.py
Your first variable is: first
Your second variable is: 2nd
your third variable is: 3rdroot@db1:~/share/python/Hardway# python second.py apple orange grapefruit
The script is called: second.py
Your first variable is: apple
Your second variable is: orange
your third variable is: grapefruit
可以将后面几个参数替换为任意的输入,当参数个数正确,得到相应的输出
注意:
1、这涉及到argv与raw_input的对比
差异:在于用户输入的时机,如果在用户执行命令时就要输入,那就是argv,如果在脚本运行时输入,那就是raw_input()
相同点:二者输入全部为字符串,如果想要得到数字或者其他类型,需要强制类型转换
习题14、提示和传递
代码段:
from sys import argv
script, user_name = argv
prompt = ' > '
print "Hi %s, I'm the %s script."%(user_name, script)#script 脚本
print "I'd like to ask you a few questions."
print "Do you like me %s?" %user_name
likes = raw_input(prompt)
print "Where do you live %s?"%user_name
lives = raw_input(prompt)
print "What kind of computer do you have?"
computer = raw_input(prompt)
print """
Alright, so you said %r about liking me.
you live in %r.Not sure where that is
And you have a %r computer. Nice.
"""%(likes, lives, computer)
执行过程:
root@db1:~/share/python/Hardway# python second.py db
Hi db, I’m the second.py script.
I’d like to ask you a few questions.Do you like me db?
yes
Where do you live db?
XIDIAN UNIVERSITY
What kind of computer do you have?
ACER结果:
Alright, so you said ‘yes’ about liking me.
you live in ‘XIDIAN UNIVERSITY’.Not sure where that is
And you have a ‘ACER’ computer. Nice.
注意:
1、将用户提示符设置为变量Prompt,这样就不需要在每次用到raw_input时重复输入提示用户的字符了,而且将提示符修改为别的字符串,只需要修改一个位置就可以了
2、这里argv参数接收用户输入的名字
3、成对的三个引号可以定义多行字符串,而%是字符串的格式化工具
习题15、读取文件
代码段:
from sys import argv
script, filename = argv
txt = open(filename)
print "Here's your file %r: " %filename
print txt.read()
txt.close()
print "Type the filename again: "
file_again = raw_input(">")
txt_again = open(file_again)
print txt_again.read()
txt_again.close()
结果:
root@db1:~/share/python/Hardway# python second.py ex15_sample.txt
Here’s your file ‘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
Happy National Day!
Type the filename again:
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
Happy National Day!
注意:
1、在读取文件之前,要在当前目录下创建一个txt文件
2、涉及文件的打开及读取操作 pydoc file 获取更多信息
习题16、读写文件
代码段:
#cong sys软件包中引入argv特性,以供使用
from sys import argv
#argv中参数包括Python脚本代码名字,及要操作的txt文件名字
script, filename = argv
print "We are going to erase %r." %filename
print "If we don't want that, hit CTRL-C"
print "If you want do this, hit RETURN."
raw_input("?")
print "opening the file..."
#打开文件,可写
target = open(filename, 'w')
print "Truncating the file. Goodbye!"
#清空文件内容
target.truncate()
print "Now I'm going to ask you for three lines."
line1 = raw_input("line1: ")
line2 = raw_input("line2: ")
line3 = raw_input("line3: ")
print "I'm going to write those to the file."
#写入字符串及换行符
target.write(line1)
target.write("\n")
target.write(line2)
target.write("\n")
target.write(line3)
target.write("\n")
print "And finally, we close it."
target.close()
执行过程:
root@db1:~/share/python/Hardway#
python second.py ex15_sample.txt
We are going to erase ‘ex15_sample.txt’.
If we don’t want that, hit CTRL-C
If you want do this, hit RETURN.
?
opening the file…
Truncating the file. Goodbye!
Now I’m going to ask you for three lines.
line1: Happy National day
line2: I can learn python
line3: i’m very happy
I’m going to write those to the file.
And finally, we close it.
结果:
ex15_sample.txt**文件中内容:**
Happy National day
I can learn python
i’m very happy
注意:
close ————————————— 关闭文件
read ———————————— 读取文件内容
readline ——————— 读取文本文件的一行
write(stuff)———————将stuff写入文件中
open(filename, ‘w’) ‘w’写,‘r’读,‘a’append 追加
习题17、更多文件操作
代码段:
#引入变量参数列表argv
from sys import argv
#引入exists用以判定文件是否存在
from os.path import exists
#argv中需要包含脚本名字,拷贝数据的原文件及目标文件名
script, from_file, to_file = argv
print "Copying from %s to %s" %(from_file, to_file)
#we could do these two on one line too, how?
#打开文件,并且读出数据
in_file = open(from_file)
indata = in_file.read()
#由len()获取数据长度信息
print "The input file is %d types long" %len(indata)
#判断目标文件是否存在
print "Dose the output file exist? %r" %exists(to_file)
print "Ready, hit RETURN to continue, CTRL-C to abort"
raw_input()
#打开目标文件,并且将数据写入
out_file = open(to_file, 'w')
out_file.write(indata)
print "Alright, all done."
#关闭原文件及目标文件
out_file.close()
in_file.close()
过程:
root@db1:/home/db/share/python/Hardway#
python second.py ex17_from.txt ex17_to.txtCopying from ex17_from.txt to ex17_to.txt
The input file is 53 types long
Dose the output file exist? True
Ready, hit RETURN to continue, CTRL-C to abortAlright, all done.
结果:
完成了文件内容复制,ex17_to.txt文件内容为:
Happy National day
I can learn python
i’m very happy
注意:
print "The input file is %d types long" %len(indata)
代码语句执行时,报语法错误
发现在%len(indata)前面多加了逗号
习题18、命名、变量、代码和函数
代码段:
#this one is like your script with argv
def print_two(*args):
arg1, arg2 = args
print "arg1: %r, arg2: %r" %(arg1, arg2)
#ok, that's *args is actually pointless(无意义的), we can just do this
def print_two_again(arg1, arg2):
print "arg1: %r, arg2: %r" %(arg1, arg2)
#this just take one argument
def print_one(arg1):
print "arg1: %r" %arg1
#this one takes no arguments
def print_none():
print "I got nothing"
print_two("apple", "banana")
print_two_again("apple1", "banana1")
print_one("Only_apple")
print_none()
结果:
arg1: ‘apple’, arg2: ‘banana’
arg1: ‘apple1’, arg2: ‘banana1’
arg1: ‘Only_apple’
I got nothing
注意:
1、在第一遍执行的时候,print_two(apple, banana)报错,提示name ‘apple’ is not defined
2、输入应该为字符串,或者变量,这里加上了引号,执行正确,另外python提示报错用的是name,是名字,不是Variable
3、*args里面的功能是告诉python把函数所有参数都接收进来,然后放进名叫args的列表中
4、函数定义def、函数名字print_two、 (形参量)、冒号:、Table(四个空格)函数体、调用
习题19、函数和变量
代码段:
#cheese是奶酪,crackers是薄脆饼干,打印二者的数量
def cheese_and_crackers(cheese_count, boxes_of_crackers):
print "You have %d cheeses!" %cheese_count
print "You have %d boxes of crackers!" %boxes_of_crackers
print "Man that's enough for a party"
print "Get a blanket.\n"
#函数实参可以直接使用数字
print "We can give the function numbers directly: "
cheese_and_crackers(20, 30)
#函数实参可以使用脚本中的变量
print "OR, we can usr variables from our script :"
amount_of_cheese = 10
amount_of_crackers = 50
cheese_and_crackers(amount_of_cheese, amount_of_crackers)
#函数实参可以使用数学运算
print "We can even do math inside too: "
cheese_and_crackers(10+20, 5+6)
#函数实参可以使用变量与数字的数学运算,其实等价于常量的数学运算,变量这里传递进来一个值
print "And we can combine the two, variables and math:"
cheese_and_crackers(amount_of_cheese + 100, amount_of_crackers + 1000)
结果:
We can give the function numbers directly:
You have 20 cheeses!
You have 30 boxes of crackers!
Man that’s enough for a party
Get a blanket.OR, we can usr variables from our script :
You have 10 cheeses!
You have 50 boxes of crackers!
Man that’s enough for a party
Get a blanket.We can even do math inside too:
You have 30 cheeses!
You have 11 boxes of crackers!
Man that’s enough for a party
Get a blanket.And we can combine the two, variables and math:
You have 110 cheeses!
You have 1050 boxes of crackers!
Man that’s enough for a party
Get a blanket.
注意:
1、代码展示了函数cheese_and_crackers的不同传参方式,函数会将传入的内容打印出来
2、可以给函数传递数字、变量、数学表达式、甚至将数学表达式与变量结合使用
3、用户想要输入数字 int(raw_input(字符串)), 将输入的字符串强制类型转换为Int即可
—————————————————————————————————————————————————————
习题20、函数和文件
代码段:
#引入变量列表argv,包括脚本名,输入文件名
from sys import argv
script, input_file = argv
#打印文件全部内容
def print_all(f):
print f.read()
#f.seek(0)回到文件文件的开始
def rewind(f):
f.seek(0)
#打印行号及单行内容
def print_a_line(line_count, f):
print line_count, f.readline()
#打开文件
current_file = open(input_file)
print "First let's print the whole file: \n"
print_all(current_file)
print "Now let's rewind, kind of like a tape."
rewind(current_file)
print "Let's print three lines: "
current_line = 1
print_a_line(current_line, current_file)
current_line += 1
print current_file.tell()
print_a_line(current_line, current_file)
current_line += 1
print_a_line(current_line, current_file)
执行过程:
root@db1:/home/db/share/python/Hardway# python second.py ex20.txt
结果:
First let’s print the whole file:
Python is my favorite language
simple
efficient
Now let’s rewind, kind of like a tape.
Let’s print three lines:
1 Python is my favorite language
32
2 simple
3 efficient
注意:
1、seek本意是寻找,使用pydoc file 可以找到seek的解释说明
2、seek() 移动至新的文件位置,seek(0)初始位置,seek(1)当前位置,seek(2)文件末尾位置
3、tell()返回当前文件位置,一个整数值 这里面在print current_file.tell() 返回值为19 是以字节计算的
4、执行结果出现了间隔空行,因为readline()函数返回的内容中文件本来就有\n
5、而print在打印时又会添加一个\n,这样一来多出一个空行,解决办法是在print 语句结尾加一个逗号(,)
6、seek()函数的处理对象是字节而非行,所以seek(0)只是转到文件的0byte, 也就是第一个字节位置
7、readline()里面的代码会扫描文件的每一个字节,直到找到一个\n为止,然后它停止读取文件,并且返回此前文件内容,文件f会记录每次调用readline()后的读取位置,它就可以在下次调用时读取接下来一行