2013-06-21 58 views
1

我寫了這個示例程序,用於打開計算機中的文本文件(database1.txt),並顯示當前文件中的結果。然後提示使用是否他們的名字在文件中,如果是則應打印文本文件的內容然後關閉,否則應提示用戶輸入他們的名字,然後程序將該名字寫入同一文本文件,然後再次打印文本文件的內容,以便用戶可以看到新添加的數據。我輸入了代碼,不知何故,它一直說我有一個語法錯誤。我檢查了幾次,我無法修復這個錯誤。我想知道是否有人可以看看,如果他們能夠向我解釋錯誤。謝謝Python(最新版本)語法錯誤

#This program reads/writes information from/to the database1.txt file 

def database_1_reader(): 
print('Opening database1.txt') 
f = open('database1.txt', 'r+') 
data = f.read() 
print data 
print('Is your name in this document? ') 
userInput = input('For Yes type yes or y. For No type no or n ').lower() 
if userInput == "no" or userInput == "n" 
    newData = input('Please type only your First Name. ') 
    f.write(newData) 
    f = open ('database1.txt', 'r+') 
    newReadData = f.read() 
    print newReadData 
    f.close() 
elif userInput == "yes" or userInput == "ye" or userInput == "y" 
    print data 
    f.close() 
else: 
    print("You b00n!, You did not make a valid selection, try again ") 
    f.close() 
input("Presss any key to exit the program") 
database_1_reader() 
+0

使用'with'處理文件時,它會自動關閉該文件爲您服務。 –

回答

3

print是py3.x功能:

print newReadData 

應該是:

print (newReadData) 

演示:

>>> print "foo" 
    File "<ipython-input-1-45585431d0ef>", line 1 
    print "foo" 
      ^
SyntaxError: invalid syntax 

>>> print ("foo") 
foo 

小號tatements這樣的:

elif userInput == "yes" or userInput == "ye" or userInput == "y" 

可以簡化爲:

elif userInput in "yes"