笨辦法學Python習題14 提示和傳遞
阿新 • • 發佈:2019-02-16
這個習題只要是raw_input與引數變數的結合使用!
前面的西體重raw_input()內可以寫一些“XXX”提問的內容。那麼raw_input()括號內可以填寫替他的內容嗎?
先上程式碼:
from sys import argv script, user_name = argv prompt = '>' print "Hi %s, I'm the %s script."%(user_name,script) print"I'd like 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)
執行結果如下:
Hi simengred, I'm the ex14.py script. I'd like ask you a few questions. Do you like me, simengred? >yes Where do you live, simengred? >shenzhen What kind of computer do you have? >macbook Alright,so you said 'yes' about liking me. you live in 'shenzhen' .Not sure where that is. And you have a 'macbook' computer .Nice.
1,從程式碼中可知raw_input(),括號中也可以填寫變數,變數的內容為“>”在執行程式時,>起到一個提示輸入的作用。
2,程式碼的引數變數argv部分,算是對習題13的複習。
從terminal中輸入的引數ex14.py 和simengred傳遞給argv.
再有argv解包將ex14.py賦值給script,simengred賦值給user_name
再通過格式化控制符,將這些值“鑲嵌”到句子中。