python - 我已经编写了一些代码,我正在尝试使用“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")
我只是想设置我的循环然后我会完成我的代码。
解决方案
三件事:
- Python 的独特之处在于空格很重要——同一块中的代码应该具有相同的缩进
- Else 语句只能在 if 语句之后使用。由于您的代码中没有任何 if 语句,因此您不能有任何 else 语句。我们可以删除它们。
- 您需要询问用户他们是否想在循环结束时继续进行。
这是您的代码的清理版本:
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")
推荐阅读
- excel - 创建PPT表格运行缓慢
- windows - 有谁知道根据 DNS 客户端确定服务的命令?
- python - “无法读取 null 的属性‘toFixed’”
- javascript - JavaScript 根据键值数组从列表中删除对象
- django - 在 Heroku 部署期间无法填充数据库表?
- javascript - 用值交换键
- r - 绘图的 Rmarkdown 问题(PDF 输出)
- amazon-dynamodb - 通过 API Gateway 代理的 BatchGetItem 中的 SerializationException
- swift - 获取 SwiftUI 视图大小并将其写入模型的正确方法
- android - 检测 App android 是否处于 Debug 或 Release