这个python代码有什么问题

时间:2015-03-15 14:20:10

标签: python

print ("You have two choices:", \n "(1) Get up now", \n "or," \n "(2) Sleep some more and wait till morning")

我真的不明白这段代码有什么问题。当我运行它时,Python说“行后续字符有一个意想不到的字符”,我不明白。

2 个答案:

答案 0 :(得分:2)

将换行符放在双引号内。

In [44]: print("You have two choices:",  "\n(1) Get up now",  "\nor,"  "\n(2) Sleep some more and wait till morning")
You have two choices: 
(1) Get up now 
or,
(2) Sleep some more and wait till morning

答案 1 :(得分:2)

首先,要解决您的问题,请注意换行符\n应该在里面引号,即字符串文字本身的一部分:

print ("You have two choices:\n(1) Get up now\nor\n(2) Sleep some more and wait till morning")

其次,错误消息的原因是反斜杠\ 外部引号用于表示"此逻辑行继续在下一个物理行上&# 34; ,即explicit line joining。这意味着例如:

if some_really_long_predicate and \
        this_other_thing:
    print("We're here now")

是可以接受的,虽然在括号is preferred中隐式延续:

if (some_really_long_predicate and
        this_other_thing):
    print("We're here now")

因此当Python解析时:

print ("You have two choices:", \n ...
                              # ^ continuation character

它不期望找到n"意外字符" 有问题)或任何后续字符。


最后,请注意您可以使用多行字符串将其写得更整齐:

print("""You have two choices:
(1) Get up now
or
(2) Sleep some more and wait till morning""")
                                       # ^ note triple quotes

(参见here了解如何在缩进的块中制作这个整理器。)