2016-12-02 63 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

感謝您的幫助,現在一切都保持完好,因爲你。我無法感謝你的幫助 - 我現在有一個工作程序,不只是說「嗨」哈哈。非常感謝, –