2016-12-02 93 views
-2

最近我一直在玩Python,并且在创建函数时碰到过这个错误。我似乎无法修复它:(CODE: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() 
+0

是这部分功能吗?很难说。记得在python中,缩进定义范围。你的第一行(从'choice'开始)不与'直接在它下面的行对齐。可能是你在StackOverlow中的格式,但我怀疑它。返回代码并确保同一范围内的行对齐。 –

+3

错误的格式化代码是您的问题。我提到你在提出模糊问题之前阅读关于Python的基础知识。 – dannyxn

回答

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() 
+0

我认为定义“if”块之外的函数是明智的,因为这种布局可能被错误地解释为函数应该在运行中定义(这正是我想象的OP所想的) – roganjosh

+1

我同意,I倾向于尽量让代码尽可能接近OP的原始代码,但是你是对的,可能会导致错误解释最佳实践。将更新,谢谢 – davedwards

+0

感谢您的帮助,现在一切都保持完好,因为你。我无法感谢你的帮助 - 我现在有一个工作程序,不只是说“嗨”哈哈。非常感谢, –