学习python的第七天

提示和传递

本节的学习是同时使用argvraw_input向用户提示一些特别的问题。下一节学习读写文件,这节练习是下一节的基础,所以得研究清楚。下边的练习使用raw_input打出简单的>作为提示符,提示用户输入。在书中说明这节学习的方式和ZorkAdventure两款游戏类似。Zork

练习部分

from sys import argv

user_name = raw_input("Your name: ")
script, user_name = argv,user_name
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 = 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 taht is.
And you have a %r computer. Nice.
""" % (likes, lives, computer)
  • prompt的作用是把提示符>设置为变量,在以后的代码中就不用重复输入。

加分习题

user_name = raw_input("Your name: ")
user_address = raw_input("Your adress:")
user_name = user_name
prompt = '> '

print "Hi %s, I'm the Robot." % user_name
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_address
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 taht is.
And you have a %r computer. Nice.
""" % (likes, lives, computer)

读取文件

这节练习涉及到两个文件。一个是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.

我们下一步需要做的是用脚本“打开”,然后打印出来。我们利用argvraw_input这样可以从用户获取信息,然后处理文件。

练习部分

from sys import argv

#输入要读取的文件名
filename = raw_input("Filename:")
#解压
script, filename = argv, filename
#打开输入的文件
txt = open (filename)
#“这是你的文件”
print "Here's your file %r:" % filename
#文件内容
print txt.read()
#再次读取文件内容
print "Type the filename again:"
file_again = raw_input("> ")
txt_again = open(file_again)
print txt_again.read()

代码的作用是先获取需要打开的文件名,然后解压读取文件,再打印文件内容。需要提示的是txt文件必须和ex15.py这个文件放在一起。要不然会报错,提示找不到文件。在代码中我们看到了新奇的东西,我们在txt上调用了一个函数。从open获得的东西是一个file(文件),文件本身也支持一些命令。接受命令的方式是使用句点.(英文是dotperiod),紧跟着你需要的命令,然后是类似openraw_input一样的参数。

你可能感兴趣的:(笨办法学python)