python - 如何修复 IndentationError 突破 If Else?
问题描述
我试图在使用else
条件下突破,break
但它给了我IndentationError
:
import json
import difflib
from difflib import get_close_matches
data=json.load(open("data.json"))
def translate(word):
word=word.lower()
if word in data:
return data[word]
elif len(get_close_matches(word,data.keys()))>0:
yn= input("Did you mean %s instead. Type Y if you want to look up %s or Type any other key if you want to leave" % get_close_matches(word,data.keys())[0])
if yn=="Y":
return get_close_matches(word,data.keys())[0]
else:
break
else:
return ("This word does not exist in the data, please check the word again")
user_word=input("Please enter your word:\n")
print(translate(user_word ))
解决方案
Python 期望每个循环或条件语句的第一行代码缩进一个额外的制表符(基本上任何以 ':' 结尾的东西)
所以缩进两次来解决这个问题。但是,您可能实际上并不想在这里休息,您可能想返回。
这是缩进休息
import json
import difflib
from difflib import get_close_matches
data=json.load(open("data.json"))
def translate(word):
word=word.lower()
if word in data:
return data[word]
elif len(get_close_matches(word,data.keys()))>0:
yn= input("Did you mean %s instead. Type Y if you want to look up %s or Type any other key if you want to leave" % get_close_matches(word,data.keys())[0])
if yn=="Y":
return get_close_matches(word,data.keys())[0]
else:
break
else:
return ("This word does not exist in the data, please check the word again")
user_word=input("Please enter your word:\n")
print(translate(user_word ))
但你可能想要
import json
import difflib
from difflib import get_close_matches
data=json.load(open("data.json"))
def translate(word):
word=word.lower()
if word in data:
return data[word]
elif len(get_close_matches(word,data.keys()))>0:
yn= input("Did you mean %s instead. Type Y if you want to look up %s or Type any other key if you want to leave" % get_close_matches(word,data.keys())[0])
if yn=="Y":
return get_close_matches(word,data.keys())[0]
else:
return # or return ""
else:
return ("This word does not exist in the data, please check the word again")
user_word=input("Please enter your word:\n")
print(translate(user_word ))
编辑以获取更多信息:在 python 中,break 用于提前退出循环,如这些示例中所做的那样如果您在不在循环内时尝试中断,您将得到一个SyntaxError: 'break' outside loop
推荐阅读
- vb.net - VB 模式导入模式加载异步
- reactjs - google 使用 GatsbyJS 时如何知道要抓取哪些页面
- node.js - 将 AWS DocumentDB 与 Sail.js 配置结合使用
- powershell - PowerShell 数字
- c# - 两个年龄范围之间的列上的 Datagrid 过滤器
- firebase - 如果未设置激活事件,用户何时会接触到 Firebase A/B 测试?
- javascript - unslick() 不破坏整个轮播
- google-chrome - Chrome 71 桌面上的音频元素强制自动播放失败
- python - 将数据框值旋转并连接到新列中
- python - 如何使用.loc在for循环中将数据框行附加到另一个?