Exercises 11python
代碼函數
# -*- 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
code
代碼對象
# -*- 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)
輸出ip
Notesutf-8
①本節練習對比上節添加了raw_input()輸入函數的提示符,無新內容ci
②加分習題
可知 命令行中輸入"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()函數用相同的提示符,修改變量就能夠修改所有的提示符