请帮助正确的缩进缩进

时间:2019-07-24 19:00:17

标签: python python-3.x

我正在尝试在break条件下使用else来打破循环,但这给了我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 ))

1 个答案:

答案 0 :(得分:0)

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用于像these examples中那样提前退出循环,如果您尝试在不处于循环内时中断,则会得到SyntaxError: 'break' outside loop