03笨方法学Python|03笨方法学Python|ex11-17

ex11 1.raw_input 和 input 的区别 raw_input() ,无论什么输入内容,python都把内容看成一个字符串string.
input ,python会根据输入的内容,决定其类型。Shawn建议避免使用此命令。

代码错误。。MARK在此,待改。 print "what year is it this year?", year = int(raw_input()) if year % 4 == 0**??? invalid** print "this is a leap year" else print "not leap year"

leap year: 闰年
2. 附加练习:乘幂计算练习,熟悉数字类型int 和 float
print "Give me a base", base = float(raw_input()) print "Give me then a exponent which is a integer.", exponent = int(raw_input()) ans = base ** exponent print "So the answer for %.f to the power %d is %f." % (base,exponent,ans)

以上代码运行后,如果在指数exponent 那里输入3.1,就会报错:
数字类型int 和 float
  • float函数将整数和字符串转换成浮点数。
  • int函数能够
    把符合数学格式的数字型字符串转换成整数
    把浮点数转换成整数,但是只是简单的取整,而非四舍五入。
所以如果想变成整数,需要先转成浮点,再转成整数。
print "Les't do some exponentiation." print "Give me a base", base = float(raw_input()) print "Give me then a exponent which is a integer.", exponent = int(float(raw_input())) ans = base ** exponent print "So the answer for %.2f to the power %d is %.2f." % (base,exponent,ans)

格式符 %.4f 表示保留4位小数。
查看帮助
python -m pydoc 命令名

pydoc 在线帮助系统 https://docs.python.org/2.7/library/pydoc.html
ex12 简化上面的乘幂计算例子
base = float(raw_input("Give me a base.")) expo = int(float(raw_input("Give me a exponent."))) ans = base ** expo print "So the answer for %d to the power %.2f is %.4f." %(base,expo,ans)

【03笨方法学Python|03笨方法学Python|ex11-17】第一行,引号前面的空格,在powershell里才体现出是空格。
ex13
from sys import argvscript,first,second,third = argvprint "The script is called:",script print "Your first variable is:",first print "Your second variable is",second print "Your third variable is:",third

如上按书中一字不差打完代码后,我一如既往在powershell里敲入
python ex13.py

然后就看到这样的错误提示:
Traceback (most recent call last): File "ex13.py", line 3, in script,first,second,third = argv ValueError: need more than 1 value to unpack

解释:代码没错,但是在powershell里要输入的东西多了 3个任意变量!正好三个,不可多不可少,以空格区分。
比如这样的,
python ex13.py aa bb cc

为什么呢?因为小白如我,根本没有理解这节课,没有理解sys.argv,看了stackoverflow上这位高手的回答,才算清晰。
这节课讲的还是如何给python“喂食”,输入变量。
sys模块,argv是其中的一个函数。argv表示一串参数(a tuple of arguments). 第一行 from sys import argv,表示从sys模块调出这么一串参数。
那这一串参数到底是啥呢?4个变量并排放置,暂时被命名script,first,second,third.
所以可以把argv看成一个行向量[a,b,c,d],然后具体计算再带入具体数值。在powershell中,我们敲进去的,在python后面的内容,按空格区分,分别被带入这个“向量”里。
比如这一课我们完全可以这么敲
from sys import argv aa,bb,cc,dd = argv#define what is this argv print "The first variable is called:",aa print "Your 2ndis:",bb print "Your 3rd is",cc print "Your 4th is:",aa

在powershell敲入 python ex13.py 11 22 33,看见以下结果
The first variable is called: ex13.py Your 2ndis: 11 Your 3rd is 22 Your 4th is: ex13.py

故意不用33,哈哈。
ex14 ex14和13大同小异。
不如再次理解sys.argv. How to use sys.argv in Python
sys 是System-specific parameters and functions的缩写,表示python内置的各种参数和方程。sys.argv表示一个清单,清单内容需要用命令行输入。
试试下面的代码,就更清楚了~
argv[0]表示代码文件的名字
函数len(sys.argv) 可以看这个argv清单中有几个参数。
函数str(),将括号里内容转换成字符串。
import sys print "This is the name of the script: ",sys.argv[0] print "Number of arguments: ",len(sys.argv) print "The arguments are: ",str(sys.argv)

测试两次,看到的结果分别为:
$ PS D:\105-coding\learnpython> python ex14_sys.py This is the name of the script:ex14_sys.py Number of arguments:1 The arguments are:['ex14_sys.py']$ PS D:\105-coding\learnpython> python ex14_sys.py 11 22 33 This is the name of the script:ex14_sys.py Number of arguments:4 The arguments are:['ex14_sys.py', '11', '22', '33']

Zork 在线版本 zork online, 这个网站上全是类似的文字型游戏,好有爱啊~
Adventure没找到。
ex15
  • 输入filename时要带类型。 ex15_sample.txt 后缀不能省略。
  • file 与 file object 的区别
    open命令可以返回(也就是生成)一个 file object(文件对象)。File object相当于这个file的管理者,也叫作handle。我们对file的各种操作都需要通过这个管理者/把手来进行。包括read,write,close等等。
    使用open时,要告诉电脑,用什么模式Mode打开,不写的话就是默认“只读模式”。
mode description
'r' Open a file for reading. (default)
'w' Open a file for writing. Creates a new file if it does not exist or truncates the file if it exists.
'r+' open a file for both reading and writing.
'a' open a file for adding a data to the end of file.
  • 我们把file object可以对file进行的各种操作,叫做method.
    常用的method如下。
method description
close() Close an open file. It has no effect if the file is already closed.
read(n) Read atmost n characters form the file. Reads till end of file if it is negative or None.
readline(n=-1) Read and return one line from the file. Reads in at most n bytes if specified.
seek(offset,from=SEEK_SET) Change the file position to offset bytes, in reference to from (start, current, end).
truncate(size=None) Resize the file stream to size bytes. If size is not specified, resize to current location.
write(s) Write string s to the file and return the number of characters written.
摘自 programmiz/file-operation
  • 课后题:Start python again and use open from the prompt. Notice how you can open files and run read on them right there?
>>> showme = open("ex15_sample.txt") >>> print(showme.read()) This is stuff I typed into a file. It is really cool stuff. Lots and lots of fun to have in here. >>> showme.close() >>>

  • 其他参考:
    全面讲解file相关操作:
    http://www.pythonforbeginners.com/files/reading-and-writing-files-in-python
    http://www.diveintopython.net/file_handling/file_objects.html
    https://www.pythoncentral.io/reading-and-writing-to-files-in-python/
只用open,read命令,一次只能打开一个文件。如果要同时打开多个file,比较复杂,涉及另一个函数,解答在下面链接里,暂时略过。
https://stackoverflow.com/questions/4617034/how-can-i-open-multiple-files-using-with-open-in-python
https://stackoverflow.com/questions/30041837/how-to-open-multiple-files-one-by-one-and-print-the-contents-in-python
ex 16
  • 附加练习3
    仅使用一次命令target.write,完成练习。
target.write(line1,"\n",line2,"\n",line3,"\n")

报错。
File "ex16.py", line 25, in target.write(line1,"\n",line2,"\n",line3,"\n") TypeError: function takes exactly 1 argument (6 given)

可行的命令:
ff = "%s\n%s\n%s\n" %(line1,line2,line3) target.write(ff)

  • 附加练习6
    如果用write mode打开文件,不需要truncate了。因为w模式下,写的东西直接覆盖原内容。
    如果只是想在原来文件内容后面加东西,进入append模式,“a”.
ex17
  • 一行改写原代码Line 9,10
indata = https://www.it610.com/article/open(from_file).read()

  • 附加题3 用一行来重写本节练习。
from sys import argv ; open(argv[2], 'w').write(open(argv[1]).read())

或者使用更高级的代码。
import shutil, sys ; shutil.copy(sys.argv[1], sys.argv[2])

  • 附加题5 找出为什么你需要在代码中写 output.close() ?
    我删掉了这行,发现也没关系。。

    推荐阅读