2017-04-25 29 views
0

我已經開始學習Python 2.7.x的「Learn Python the Hard Way」一書。我目前正在學習raw_input函數,我正在嘗試使用它的不同方法。我寫了下面的代碼:如何將變量插入到raw_input查詢中?

name = raw_input("What is your name? ") 
print "Hi %s," % name, 
home = raw_input("where do you live? ") 

print "I hear that %s is a great place to raise a family, %s." % (home, name) 

age = raw_input("How old are you, %s? ") % name 

我收到此錯誤與最後一行:

TypeError: not all arguments converted during string formatting

我如何使用raw_input功能以類似的方式,並插入一個變量,以便自定義問題嵌入在raw_input查詢(道歉,如果我弄亂術語)?

理想情況下,我想輸出沿着這些路線的一個問題:

How old are you, Bob?

回答

4

嘗試:

age = raw_input("How old are you, %s? " % name) 

說明:

raw_input([prompt]) 

If the prompt argument is present, it is written to standard output without a trailing newline. The function then reads a line from input, converts it to a string (stripping a trailing newline), and returns that. 

所以,當你這樣做,

age = raw_input("How old are you, %s? ") % name 

讓我們說你進入Paul

所以上面的語句而成,

age = "Paul" % name 

而且由於字符串「保羅」是不是會引發相應的錯誤的佔位符。

+0

這似乎並不奏效。查詢變成:「你多大了,%s?」當我回應時,我看到了同樣的錯誤。 –

+0

你試過'age = raw_input(「你幾歲,%s?」%name)''? – JkShaw

+0

完美,工作。謝謝! –