我已經決定學習如何編程,並且因爲這是每個人都先推薦的,我已經開始編寫Python了。我已經學會了我的基本知識,最近搞清楚了if/else語句。我認爲這是一個小小的挑戰,我可能會嘗試應用大部分我學到的東西,並掀起一個做一些事情的小程序。所以我試圖製作一個腳本,可以讀取文件或查找特定單詞是否在文件中,從而爲用戶提供選擇。這是我寫的代碼,並且不起作用。找不到Python中的if/else語法
print "Hello, would you like to read a file or find whether or not some text is in a file?"
choice = raw_input("Type 'read' or 'find' here --> ")
if choice == "read":
readname = raw_input("Type the filename of the file you want to read here -->"
print open(readname).read()
elif choice == "find":
word = raw_input("Type the word you want to find here --> ")
findname = raw_input("Type the filename of the file you want to search here --> ")
if word in open(findname).read():
print "The word %r IS in the file %r" % (word, filename)
else:
print "The word %r IS NOT in the file %r" % (word, filename)
else:
print "Sorry, don't understand that."
我是一個徹底的磨合,你可以通過查看代碼告訴,但無論如何,幫助將不勝感激。首先,Python在print
上給我一個語法錯誤。當我標出它上面的變量行時,它不會給我錯誤,所以我想這裏有一個問題,但我在Internet上找不到任何東西。另外,如果我像我說的那樣標出變量行,但在運行它時鍵入「find」(運行elif
部分),我得到一個錯誤,說明findname
未定義,但我找不到它爲什麼不會?無論如何,我敢肯定這顯然是明顯的,但嘿,我正在學習,如果你們中的任何人會告訴我爲什麼這個代碼很糟糕,我會愛你:)
如果你正在使用python 3+,則因爲打印的語法存在對打印會引發錯誤: 打印(「一些文本」) – PabTorre