Python:循环提示返回

时间:2016-08-06 03:54:46

标签: python if-statement

这个Python文件的许多错误已得到修复,但还有最后一件事无效。如果既不输入是也不是,我需要使用else语句循环返回再次询问问题。您可以通过代码看到我的目标,但我可能甚至没有走上正确的轨道。有人可以帮助我最后一件事吗?

#These are my variables which are just strings entered by the user.
friend = raw_input("Who is your friend? ")
my_name = raw_input("Enter Your Name: ")
game_system = raw_input("What's your favorite game system? ")
game_name = raw_input("What's your favorite game for that system? ")
game_status = raw_input("Do you have the game? (Yes or No) ")
game_store = raw_input("What is your favorite game store? ")
game_price = raw_input("What's the price of the game today? Enter a whole number. ")

#This is what is printed after all the prompts. There is no condition for this print.
print "I went outside today and my friend " + friend + " was outside waiting for me. He said \"" + my_name + ", did you get the new " + game_system + " game yet? You were getting " + game_name + " today, right?\""

#If the condition on the Yes or No question is yes, then this code runs.
if game_status == "YES":
    print "\"You know I got it, man!\" I said. \"Awesome! Let's play it,\" he said. \"I heard " + game_name + " is supposed to be amazing!\" We went back inside and took turns playing until " + friend + " had to go home. Today was a fun day."

#If the condition is No, then this code runs.
elif game_status == "No":
    print "\"Well let's go get it today and we can come back here and play it!\" We went down to " + game_store + " and baught " + game_name + " for $" + str(game_price) + " and we went back to my house to take turns playing until " + friend + " went home. Today was a good day. (Now try again with the No option!)"

#If the condition meets neither Yes or No, then this code runs, sending the user back to the same question again. This repeats until a condition is met.
else:
    raw_input("That answer didn't work. Try again? Do you have the game? (Yes or No) ")

2 个答案:

答案 0 :(得分:2)

我会鼓励你在有条件的......之后总是打破新的一行......

if game_status == "YES":
    print "\"You know I got it, man!\" I said. \"Awesome! Let's play it,\" he said. \"I heard " + game_name + " is supposed to be amazing!\" We went back inside and took turns playing until " + friend + " had to go home. Today was a fun day."

在&#34之后缩进的任何内容;如果是game_status:"会跑。它读起来更好。

编辑 ::如果您对所有字符串使用单引号,那么您不需要转义双引号...

    print '"You know I got it, man!" I said. "Awesome! Let\'s play it," he said. "I heard ' + game_name + ' is supposed to be amazing!" We went back inside and took turns playing until ' + friend + ' had to go home. Today was a fun day.'

这是一个偏好的问题......但可能看起来不那么混乱。

答案 1 :(得分:2)

此:

if game_status: "YES"

不是您如何制作if声明。您正在对待它,就像语法

一样
if some_variable: some_value

如果变量具有该值,则if语句触发。实际上,语法是

if some_expression:

如果表达式求值为true,则if语句触发。如果您希望在if等于game_status时触发"YES"语句,则表达式应为game_status == "YES",因此if行应该

if game_status == "YES":

同样,elif行应该

elif game_status == "NO":