笨办法学python习题11-20

练习十一:提问

print("How old are you?",end='')
age = input()
print("How tall are you?",end='')
height = input()
print("How much do you weigh?",end='')
weight = input()
print("So, you're %r old,%r tall and %r heavy." % (age, height,weight))

.  上网查一下 Python 的  raw_input 实现的是什么功能。

python3.0以上版本支持input,默认接收的就是str类型 但是文本要带上字符转换或者input("")。在pyhton3中没差别。

2. 你能找到它的别的用法吗?测试一下你上网搜索到的例子。

3. 用类似的格式再写一段,把问题改成你自己的问题。

4. 和转义序列有关的,想想为什么最后一行  '6\'2"' 里边有一个  \' 序列。单引号需要被转义,从而防止它被识别为字符串的结尾。有没有注意到这一点?
 

练习十二:提示别人

age = input("How lod are you?")
height = input("How tall are you?")
weight = input("How much do you weight?")
print("So, you're %r old, %r tall and %r heavy." % (age, height, weight))

1.  在命令行界面下运行你的程序,然后在命令行输入  pydoc raw_input 看它说了些什么。如果你用的是 Window,那就试一下  python -m pydocraw_input 。

2. 输入  q 退出 pydoc。

3. 上网找一下  pydoc 命令是用来做什么的。

参考pydoc用法

pydoc是python自带的一个文档生成工具,使用pydoc可以很方便查看类和方法结构。

4. 使用 pydoc 再看一下  open ,  file ,  os , 和  sys 的含义。看不懂没关系,只要通读一下,记下你觉得有意思的点就行了。

习题十三:参数、解包、变量

from sys import argv
# argv 是所谓的“参数变量(argument variable)”
script, first, second, third = argv     # 将  argv “解包(unpack)”
print("The script is called: ", script)
print("Your first variable is:", first)
print("Your second variable is: ", second)
print("Your third variable is: ", third)

加分练习:

1.  给你的脚本三个以下的参数。看看会得到什么错误信息。试着解释一下。

少于三个会报错,测试可以看到,如果期望输入4个参数但实际只有三个或者更少

所以四个变量,除了第一个是接受的文件名以外,另外需要输入三个参数供接收。

2. 再写两个脚本,其中一个接受更少的参数,另一个接受更多的参数,在参数解包时给它们取一些有意义的变量名。

3. 将  raw_input 和  argv 一起使用,让你的脚本从用户手上得到更多的输入。

4. 记住“模组(modules)”为你提供额外功能。多读几遍把这个词记住,因为我们后面还会用到它

习题十四:提示和传递

from sys import argv
script, user_name = argv
prompt = '>'
 
print("Hi %s, I'm the %s script." % (user_name, script))
print("I'd like to ask you a few questions.")
print("Do you like me %s?" % user_name)
likes = input(prompt)
print("Where do you live %s" % user_name)
lives = input(prompt)
print("What kind of computer do you have?")
computer = 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))

笨办法学python习题11-20_第1张图片

1.  查一下 Zork 和 Adventure 是两个怎样的游戏。 看看能不能下载到一版,然后玩玩看。

《Zork》是一个交互式故事计算机游戏,也是电子游戏历史上最早的一款文字冒险游戏;

《Adventure》是一款由微软公司出品的解迷型冒险游戏,具有随机化的程序。

2. 将  prompt 变量改成完全不同的内容再运行一遍。

3. 给你的脚本再添加一个参数,让你的程序用到这个参数。

from sys import argv
script, user_name, age = argv
prompt = 'you may say: '
 
print("Hi %s, I known you're %s, I'm the %s script." % (user_name, age, script))
print("I'd like to ask you a few questions.")
print("Do you like me %s?" % user_name)
likes = input(prompt)
print("Where do you live %s" % user_name)
lives = input(prompt)
print("What kind of computer do you have?")
computer = 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))

4. 确认你弄懂了三个引号  """ 可以定义多行字符串,而  % 是字符串的格式化工具。

 

习题十五:读取文件

from sys import argv    # 引入模块argv(参数变量)
script, filename = argv     # 赋值
txt = open(filename)    # 打开文件
print("Here's your file %r:" % filename)    # 打印
print(txt.read())   # 打印文件内容
print("Type the filename again:")
file_again = input(">")
txt_again = open(file_again)
print(txt_again.read())
 

笨办法学python习题11-20_第2张图片

笨办法学python习题11-20_第3张图片

1. 在每一行的上面用注解说明这一行的用途。

2. 如果你不确定答案,就问别人,或者上网搜索。大部分时候,只要搜索 “python” 加上你要搜的东西就能得到你要的答案。比如搜索一下“python open”。

3. 我使用了“命令”这个词,不过实际上它们的名字是“函数(function)”和“方法(method)。上网搜索一下这两者的意义和区别。看不明白也没关系,迷失在别的程序员的知识海洋里是很正常的一件事情。

4. 删掉 10-15 行使用到  raw_input 的部分,再运行一遍脚本。

5. 只是用  raw_input 写这个脚本,想想那种得到文件名称的方法更好,以及为什么。

6. 运行  pydoc file 向下滚动直到看见  read() 命令(函数/方法)。看到很多别的命令了吧,你可以找几条试试看。不需要看那些包含  __ (两个下划线)的命令,这些只是垃圾而已。

7. 再次运行  python 在命令行下使用  open 打开一个文件,这种 open 和 read 的方法也值得你一学。

8. 让你的脚本针对  txt and  txt_again 变量执行一下  close() ,处理完文件后你需要将其关闭,这是很重要的一点。

# -*- coding: utf-8 -*-
from sys import argv
script,filename = argv
txt = open(filename)
print("Here's your file %r:" % filename)
print(txt.read())
print("Type the filename again:")
file_again = input("> ")
txt_again =open(file_again)
print(txt_again.read())
txt_close = txt_again.close()
txt_close1 = txt.close()
print(txt.closed)
print(txt_again.closed)

笨办法学python习题11-20_第4张图片

习题16:读写文件

from sys import  argv
script,filename = argv
print("we're going to erase %r." % filename)
print("If you don't want that,hit CTRL-C (^C).")
print("If you do want that ,hit RETURN.")
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 = input("line 1: ")
line2 = input("line 2: ")
line3 = input("line 3: ")
print("I'm going to write these 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()

笨办法学python习题11-20_第5张图片

加分练习

1.  如果你觉得自己没有弄懂的话,用我们的老办法,在每一行之前加上注解,为自己理清思路。就算不能理清思路,你也可以知道自己究竟具体哪里没弄明白。

2. 写一个和上一个练习类似的脚本,使用  read 和  argv 读取你刚才新建的文件。

from sys import argv
script, filename = argv
txt = open(filename)
print(txt.read())

3. 文件中重复的地方太多了。试着用一个  target.write() 将  line1 ,  line2 ,  line3 打印出来,你可以使用字符串、格式化字符、以及转义字符。

from sys import  argv
script,filename = argv
print("we're going to erase %r." % filename)
print("If you don't want that,hit CTRL-C (^C).")
print("If you do want that ,hit RETURN.")
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 = input("line 1: ")
line2 = input("line 2: ")
line3 = input("line 3: ")
print("I'm going to write these to the file.")
target.write(line1+"\n"+line2+"\n"+line3+"\n")
print("And finally,we close it.")
target.close()

笨办法学python习题11-20_第6张图片

4. 找出为什么我们需要给  open 多赋予一个  'w' 参数。

提示:  open 对于文件的写入操作态度是安全第一,所以你只有特别指定以后,它才会进行写入操作

因为open()默认是'r',即读取文本模式,不能进行写入; 所以需要指定写入模式, 用到参数w。

习题17:更多文件操作

from sys import argv
from os.path import exists
# 将文件名字符串作为参数,如果文件存在,返回True,否则返回False
script, from_file, to_file = argv
print("Copying from %s to %s" % (from_file, to_file))
in_put = open(from_file)
in_data = in_put.read()
print("The input file is %d bytes long" % len(in_data))
print("Does the output file exist? %r" % exists(to_file))
print("Ready, hit RTTURN to continue, CTRL-C to abort.")
input()
out_put = open(to_file, 'w')
out_put.write(in_data)
print("Alright, all done")
out_put.close()
in_put.close()
笨办法学python习题11-20_第7张图片

加分练习

1.  再多读读和  import 相关的材料,将  python 运行起来,试试这一条命令。试着看看自己能不能摸出点门道,当然了,即使弄不明白也没关系。

2. 这个脚本实在是有点烦人。没必要在拷贝之前问一遍把,没必要在屏幕上输出那么多东西。试着删掉脚本的一些功能,让它使用起来更加友好。

from sys import argv
script, from_file, to_file = argv
in_data = open(from_file).read()
out_put = open(to_file, 'w')
out_put.write(in_data)
out_put.close()
print(open(to_file).read())

3. 看看你能把这个脚本改多短,我可以把它写成一行。

open(to_file, 'w').write(open(from_file).read())

6. 找出为什么你需要在代码中写  output.close() 。
在第二题的代码最后有一句输出,我把它放到close之前,没有输出结果。

结合一些博客的解释,如果不写,新复制的文件不会保存内容。

out_put = open(to_file, 'w') 执行时会创建 to_file 文件,但是没内容 

out_put.write(indata) 执行时,内容会写入到 to_file 的内存数据中,但仍未写入硬盘。

只有在执行 close 时 python 才指定文本的各种操作已经结束了,不会再有任何变化,这个时候在写入硬盘可以尽可能地减少硬盘读写操作,提高效率
 

习题18:命名、变量、代码、函数

# this one is like your scripts with argv
def print_two(*args):
    arg1,arg2 =args
    print("arg1: %r,args2: %r" % (arg1,arg2))
#ok,that *args is actually pointless,we can just do this
def print_two_again(arg1,arg2):
    print("arg1: %r,arg2: %r" % (arg1,arg2))
#this just takes one argument
def print_one(arg1):
    print("arg1: %r" % arg1)
#this one takes on arguments
def print_none():
    print("I got nothin'.")
print_two("Zed","Shaw")
print_two_again("Zed","Shaw")
print_one("Fists!")
print_none()

笨办法学python习题11-20_第8张图片

为自己写一个函数注意事项 以供后续参考。你可以写在一个索引卡片上随时阅读,直到你记住所有的要点为止。注意事项如下:

1. 函数定义是以  def 开始的

2. 函数名称是以字符和下划线  _ 组成的

3. 函数名称紧跟着括号  ( 

4. 括号里可以包含参数,多个参数要用逗号隔开

5. 不能使用重复的参数名

6. 紧跟着参数的是括号和冒号  ): 

7. 紧跟着函数定义的代码使用了 4 个空格的缩进 ( indent )

8. 函数结束的位置取消了缩进 (“dedent”)

当你运行(或者说“使用 use”或者“调用 call”)一个函数时,记得检查下面的要点:

1. 调运函数时是否使用了函数的名称?

2. 函数名称是否紧跟着  ( ?

3. 括号后有无参数?多个参数是否以逗号隔开?

4. 函数是否以  ) 结尾?

按照这两份检查表里的内容检查你的练习,直到你不需要检查表为止。

最后,将下面这句话阅读几遍:

“‘运行函数(run)’、‘调用函数(call)’、和 ‘使用函数(use)’是同一个意思”

习题19:函数和变量

#习题19:函数和变量
def cheese_and_crackers(cheese_count,boxes_of_crackers):
    print("You have %d cheese!" % 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 just give the function numbers directly:")
cheese_and_crackers(20,30)

print("OR,we can use 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)

可以看出来先打印的是第一个不在方法里的print之后调用方法后在走方法里的内容。

笨办法学python习题11-20_第9张图片

笨办法学python习题11-20_第10张图片

1.  倒着将脚本读完,在每一行上面添加一行注解,说明这行的作用。

2. 从最后一行开始,倒着阅读每一行,读出所有的重要字符来。

3. 自己编至少一个函数出来,然后用 10 种方法运行这个函数。

#习题20:函数和文件
from sys import argv
script,input_file = argv
def print_all(f):
    print(f.read())

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' 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 = current_line + 1
print_a_line(current_line,current_file)

current_line = current_line + 1
print_a_line(current_line,current_file)

笨办法学python习题11-20_第11张图片

1.  通读脚本,在每行之前加上注解,以理解脚本里发生的事情。

2. 每次 print_a_line 运行时,你都传递了一个叫  current_line 的变量。在每次调用函数时,打印出  current_line 的至,跟踪一下它在 print_a_line 中是怎样变成  line_count 的。

readline会扫描文件的字节,直到找到下一个\n,停止扫描,下一次从此停止位置继续扫描。相当于一次扫描输出一行。

line_count我把它理解为是计数器,它正好和被调用的位置一样。

 

这里其实line_count要叫做位置参数,之所以调用时的参数current_line成为了函数定义时的line_count就是因为它们在定义与被调用时所处的位置是一样的。 
如果我们把函数定义时两个参数的位置对调,并保持调用的顺序不变。或者,函数定义时不变,调用时对调。都会因为行号这个整数(int)没有readline()这个方法而导致错误发生。

3. 找出脚本中每一个用到函数的地方。检查  def 一行,确认参数没有用错。

4. 上网研究一下  file 中的  seek 函数是做什么用的。试着运行  pydoc file 看看能不能学到更多。

看代码注释,seek函数将读写位置移动到文件的开头。其处理的是字节而非行。

5. 研究一下  += 这个简写操作符的作用,写一个脚本,把这个操作符用在里边试一下。
 

 

 

你可能感兴趣的:(学习笔记,python)