首页 > 解决方案 > 我已经编写了一些代码,我正在尝试使用“else”,但我不断收到错误

问题描述

我写了一些代码,它工作正常(从我无论如何都可以看到),直到我进入“其他”部分,真的我只是想建立一个简单的循环,但我不知道如何。错误是“预期声明,发现 Py:ELSE_KEYWORD 预期声明,发现 Py:COLON”

name = input("Hello, what is your name? ")

restart =  input ("Do you want to chat 'y' (type 'y' for yes) or 'n'")
while restart == "y":

 print("Hello " + name)

feeling = input("How are you today? ")

print("I'm feeling good!")

else:
print("Sorry, the restart")
else: print("goodbye")

我只是想设置我的循环然后我会完成我的代码。

标签: pythonpycharm

解决方案


三件事:

  1. Python 的独特之处在于空格很重要——同一块中的代码应该具有相同的缩进
  2. Else 语句只能在 if 语句之后使用。由于您的代码中没有任何 if 语句,因此您不能有任何 else 语句。我们可以删除它们。
  3. 您需要询问用户他们是否想在循环结束时继续进行。

这是您的代码的清理版本:

name = input("Hello, what is your name? ")

restart = input ("Do you want to chat 'y' (type 'y' for yes) or 'n'")
while restart == "y":
    print("Hello " + name)
    feeling = input("How are you today?")
    print("I'm feeling " + feeling)
    restart = input ("Do you want to chat 'y' (type 'y' for yes) or 'n'")

print("Goodbye")

推荐阅读