这是我的代码:
print "Hello, and welcome to the Slightly Interactive Autobiography of Robbie Wood."
print "Lets get started, shall we? What chapter would you like to read first?"
chapter = raw_input("Please type either 'Chapter 1', 'Chapter 2' or 'Chapter 3': ")
if chapter = "Chapter 1":
print "Chapter 1"
print chapter_one
else chapter = "Chapter 2":
print "Chapter 2"
print chapter_two
elif chapter = "Chapter 3":
print "Chapter 3"
print chapter_three
elif:
chapters = raw_input("Please type either 'Chapter 1', 'Chapter 2', or 'Chapter 3': ")
# Variables - Chapters
chapter_one = "text here..."
chapter_two = "text here..."
chapter_three = "text here..."
以下是来自终端的确切错误消息:
Last login: Fri Sep 7 17:22:59 on ttys000
Robbies-MacBook-Pro:~ robbiewood$ /var/folders/y6/kx37qgbs34124ztdgb4tphs00000gn/T/Cleanup\ At\ Startup/autobiography-368756862.498.py.command ; exit;
File "/private/var/folders/y6/kx37qgbs34124ztdgb4tphs00000gn/T/Cleanup At Startup/autobiography-368756862.497.py", line 9
else chapter = "Chapter 2":
^
SyntaxError: invalid syntax
logout
[Process completed]
有人可以帮我解决这个问题吗?我是一名初学Python编码员,我正在编写一个学校项目的“轻微互动自传”。
答案 0 :(得分:7)
第二组应为elif
,最后一组为else
案例,所有应使用==
进行相等性比较,而不是=
这是一个变量赋值:
# Define these variables *before* you use them...
# Variables - Chapters
chapter_one = "text here..."
chapter_two = "text here..."
chapter_three = "text here..."
if chapter == "Chapter 1":
print "Chapter 1"
print chapter_one
# This one should be an elif
elif chapter == "Chapter 2":
print "Chapter 2"
print chapter_two
elif chapter == "Chapter 3":
print "Chapter 3"
print chapter_three
# And the last one is an else
else:
chapters = raw_input("Please type either 'Chapter 1', 'Chapter 2', or 'Chapter 3': ")
答案 1 :(得分:1)
首先,使用==
检查两件事情是否相等,而不仅仅是=
,因为它是为作业保留的。其次,您应该使用else
更改第二个elif
,将elif
更改为else
。此外,您需要在之前定义chapter_xxx
变量。试试这个:
print "Hello, and welcome to the Slightly Interactive Autobiography of Robbie Wood."
print "Lets get started, shall we? What chapter would you like to read first?"
chapter = raw_input("Please type either 'Chapter 1', 'Chapter 2' or 'Chapter 3': ")
chapter_one = "text here..."
chapter_two = "text here..."
chapter_three = "text here..."
if chapter == "Chapter 1":
print "Chapter 1"
print chapter_one
elif chapter == "Chapter 2":
print "Chapter 2"
print chapter_two
elif chapter == "Chapter 3":
print "Chapter 3"
print chapter_three
else:
chapters = raw_input("Please type either 'Chapter 1', 'Chapter 2', or 'Chapter 3': ")
答案 2 :(得分:0)
在您的if / elif语句中将=
替换为==
。
答案 3 :(得分:0)
有两个问题:
(1)您在=
的表达式中使用赋值运算符(==
)而不是布尔比较运算符(if
) - 言。
if
语句中的表达式必须评估为True
或False
,您无法在那里进行作业。
(2) ,在elif
声明的最后,您不能拥有if
,它应该是< / p>
if BooleanExpr:
...
elif BooleanExpr:
...
elif BooleanExpr:
...
else:
...
即,如果您要使用elif
,则必须在if
之后和else
之前。
有关详细信息,请参阅Python doc re if。