【问题标题】:Python says: "expected an indented block"Python 说:“期望一个缩进块”
【发布时间】:2017-04-17 20:58:53
【问题描述】:

我最近一直在玩 Python,在创建函数时遇到了这个错误。我似乎无法修复它:(。代码:

Python

#Python

 choice = input('Append Or Write?')    
  if choice == "write":
    def write():
     pass
         text_file = open('WrittenTXT.txt', "w")
         type_user = input('Type: ')
        text_file.write(type_user)
        text_file.close()

if choice == "append":
    def append():
# Making a txt file
#Append
pass
text_file = open('WrittenTXT.txt', "a")
user_int = input('Enter An Integer: ')
 space = "\n" * 2
lines = [space, "Hi\n", "Hallo\n", "Bonjour\n", user_int]
text_file.writelines(lines)
text_file.close()

【问题讨论】:

  • 这是函数的一部分吗?很难说。记住在 python 中,缩进定义了范围。您的第一行(以choice 开头)未与其正下方的行对齐。可能是您在 StackOverlow 中的格式,但我对此表示怀疑。回顾您的代码并确保同一范围内的行对齐。
  • 格式错误的代码是您的问题。在提出晦涩的问题之前,我建议您阅读有关 Python 的基础知识。

标签: python shell cmd stack indentation


【解决方案1】:

您忘记调用您定义的函数。 pass 也可能导致函数中的语句被忽略,请删除 pass

重新格式化您的代码:

#Python

def append():
        # Making a txt file
        #Append
        # pass
        text_file = open('WrittenTXT.txt', "a")
        user_int = input('Enter An Integer: ')
        space = "\n" * 2
        lines = [space, "Hi\n", "Hallo\n", "Bonjour\n", user_int]
        text_file.writelines(lines)
        text_file.close()


def write():
    # pass
    text_file = open('WrittenTXT.txt', "w")
    type_user = input('Type: ')
    text_file.write(type_user)
    text_file.close()

choice = input('Append Or Write?')

if choice == "write":
    write()
if choice == "append":
    append()

【讨论】:

  • 我认为在 if 块之外定义函数是明智的,因为这种布局可能被错误地解释为应该动态定义函数(这就是我想象的 OP 是思考)
  • 我同意,我倾向于尝试让代码尽可能接近 OP 的原始代码,但您是对的,这可能会导致对最佳实践的误解。会更新的,谢谢
  • 感谢您的帮助,因为您,现在一切都维持得很好。我非常感谢你的帮助 - 我现在有一个工作程序,它不只是说“嗨”哈哈。非常感谢,
猜你喜欢
  • 1970-01-01
  • 2012-09-19
  • 2018-11-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-02-23
  • 2021-11-24
  • 2019-08-02
相关资源
最近更新 更多