笨方法学python-5(习题14-15)

昨天周日休息看了《我不是药神》的点映,很棒很棒,推荐!


习题十四:提示和传递

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))

关于这个问题,前面一节也提到了请教了一下师兄,就是在结构中配置一下参数。


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())


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

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

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

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

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

个人觉得input比argv好理解

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

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

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

加上之后运行结果没有什么变化,会释放这部分程序所占有的内存……


猜你喜欢

转载自blog.csdn.net/jesmine_gu/article/details/80889651
今日推荐