Exercises 11
代码
# -*- coding:utf-8 -*- print "How old are you?", age = raw_input() print "How tall are you?", height = raw_input() print "How much do you weigh?", weight = raw_input() print "So you are %r years old,%r tall and %r heavy." % (age,height,weight)
输出
Notes
①raw_input()可以让用户输入并将输入的对象赋值给变量,并且括号中可以加提示字符串。注意提示字符串输入中文时的编码问题。
# -*- coding:utf-8 -*- in_put = raw_input("中文测试".decode('utf-8').encode('gbk'))
Exercise 12
代码
# -*- coding:utf-8 -*- age = raw_input("How old are you? ") height = raw_input("How tall are you? ") weight = raw_input("How much do you weight? ") print "So you are %r old,%r tall and %r heavy." % ( age,height,weight)
输出
Notes
①本节练习对比上节添加了raw_input()输入函数的提示符,无新内容
②加分习题
可知 命令行中输入"python -m pydoc "加内建函数、模块等,可以查阅模块文档
④file的文档
⑤os的文档
⑥
Exercise 13
代码
# -*- coding:utf-8 -*- from sys import argv 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
输出
Notes
①python中用import引入新的模块,以使用模块的方法、函数等。
②argv是参数变量,代码
script, first, second, third = argv
将argv解包给等号左边的四个变量,argv由用户在运行脚本时给出运行参数,运行脚本时给出的运行参数和argv解包的变量数不等时会引发错误
③argv和raw_input()都可以从用户那里取得输入,不同点在于取得用户输入的时点。argv要求用户在执行脚本时就要输入相应的对象,raw_input()用来在脚本运行过程中取得用户的输入。
④命令汗参数同样是字符串格式,若要参与计算,需先转换成数字类型,运用int()和float()
Exercise 14
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 = 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)
输出
Notes:
①将raw_input()的提示符赋值给一个变量,这样可以修改变量达到修改提示符的目的,适用于多个raw_input()函数用相同的提示符,修改变量就可以修改全部的提示符