2015-09-30 51 views
2

我已經決定學習如何編程,並且因爲這是每個人都先推薦的,我已經開始編寫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未定義,但我找不到它爲什麼不會?無論如何,我敢肯定這顯然是明顯的,但嘿,我正在學習,如果你們中的任何人會告訴我爲什麼這個代碼很糟糕,我會愛你:)

+0

如果你正在使用python 3+,則因爲打印的語法存在對打印會引發錯誤: 打印(「一些文本」) – PabTorre

回答

3

除了通過對方的回答指出,缺少括號,你也有一個問題在這裏:

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) 

也就是說,您定義了findname,但稍後嘗試使用尚未定義的filename

我也有,你可能想看看一對夫婦建議:

  • 使用像flake8的工具給你關於你的代碼的建議(這會盡力幫助你保證你的代碼PEP8,在符合Python編碼風格指南雖然它不會捕獲代碼中的所有錯誤)
  • 嘗試使用IDE對代碼進行實時反饋。 There are many available;我個人比較喜歡PyCharm

這裏的flake8的輸出的一個示例:

$ flake8 orig.py 
orig.py:1:80: E501 line too long (92 > 79 characters) 
orig.py:5:80: E501 line too long (82 > 79 characters) 
orig.py:6:10: E901 SyntaxError: invalid syntax 
orig.py:9:80: E501 line too long (86 > 79 characters) 
orig.py:16:1: W391 blank line at end of file 
orig.py:17:1: E901 TokenError: EOF in multi-line statement 
+2

而與PEP8遵守不會使代碼更好,本身。這會使讀取和調試更容易。:) – PabTorre

+2

@PabTorre,正確,但正如你所看到的,它捕獲了阻止OP進展的SyntaxError。 – mpontillo

3

你在print以上的行上有一個缺少的鬼怪行 -

readname = raw_input("Type the filename of the file you want to read here -->" 
                      ^
                  Parantheses missing 

它應該是 -

readname = raw_input("Type the filename of the file you want to read here -->") 
0

您沒有在此線插入右括號:

readname = raw_input("Type the filename of the file you want to read here -->" 

readname = raw_input("Type the filename of the file you want to read here -->" 

通過更換這個並使用print(「」)代替打印

print("Your message here")