首页 > 解决方案 > 如何修复 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 ))

标签: pythonpython-3.x

解决方案


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


推荐阅读