2014-01-31 40 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))