无法弄清楚Python

时间:2015-09-30 03:51:21

标签: python

我决定学习如何编程,因为这是大家首先推荐的,所以我开始研究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给我一个语法错误。当我在其上面标出变量行时,它不会给我错误,所以我认为那里有一个问题,但我在互联网上找不到任何东西。另外,如果我像我说的那样标记变量行但在运行它时键入“find”(运行elif部分)我得到一个错误,说findname没有定义,但我可以找不到原因?无论如何,我确信这显然很明显,但是嘿,我正在学习,如果你们中的任何一个人告诉我为什么这个代码很糟糕,我会很高兴。)

3 个答案:

答案 0 :(得分:3)

print行 -

上方的行上缺少parantheses
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 -->")

答案 1 :(得分: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之类的工具为您提供有关代码的建议(这将帮助您确保您的代码符合Python编码风格指南PEP8。虽然它不会抓住每一个代码中的错误。)
  • 尝试使用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 :(得分: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

   print("Your message here")
相关问题