2014-01-31 42 views
-3

嗨,我試圖打印這個字符串,但我得到一個錯誤。 我的代碼有什麼問題?如何打印此字符串?

def main(): 
    for x in range (0, 100): 
     T = 100 - x 
     print (T+' bottles of beer on the wall,'+T+'bottles of beer. 
     'Take one down, pass it around,'+T-1+' bottles of beer on the wall.') 

main() 

的錯誤是:

EOL while scanning the string literal 
+1

Rom - 你需要告訴我們你得到的錯誤是什麼。當你閱讀並輸入時,它甚至可能告訴你問題是什麼...... – GreenAsJade

+0

爲什麼你不倒數計算?這樣你就不必減去。 – 1478963

+0

修正了這個問題....爲什麼downvote我? –

回答

2

有幾件事情是錯誤的:

  • 您忘記關閉您的字符串字面量;你的第一行不會以報價結束。
  • 您試圖連接字符串和整數。首先將您的整數轉換爲字符串。
  • 您沒有在您的字符串中放入足夠的空格以便在數字周圍進行適當的間距。
  • 您可能期望在Take one down之前在您的輸出中包含換行符。您必須包含明確的\n換行符或使用單獨的print語句。

更重要的是,使用逗號,而不是串聯使用print聲明內置功能:

print T, ' bottles of beer on the wall, ', T, ' bottles of beer.' 
print 'Take one down, pass it around, ', T - 1, ' bottles of beer on the wall.' 

但最好的選擇是使用字符串格式化:

print '{0} bottles of beer on the wall, {0} bottles of beer.'.format(T) 
print 'Take one down, pass it around, {0} bottles of beer on the wall.'.format(T - 1) 
+0

似乎OP是與py3 – zhangxaochen

+0

@zhangxaochen:那麼爲什麼用Python 2.7標記呢?一些新用戶仍然在'print'語句中使用括號,即使是在Python 2中。 –

+0

非常感謝:) –

0

這是更好使用format功能:

def main(): 
    for x in range (0, 100): 
     T = 100 - x 
     print('{0} bottles of beer on the wall, {0} bottles of beer. ' 
       'Take one down, pass it around, ' 
       '{1} bottles of beer on the wall.'.format(T, T-1))