Can';我不知道Python中的if/else语法

Can';我不知道Python中的if/else语法,python,Python,我决定学习如何编程,因为这是每个人首先推荐的,所以我开始编写Python。我已经学会了我认为最基本的东西,最近我弄清楚了if/else语句。我想,作为一个小小的挑战,我可能会尝试应用我学到的大部分知识,并制定一个小程序来做一些事情。因此,我试图制作一个脚本,可以读取文件或查找文件中是否有特定的单词,让用户进行选择。这是我写的代码,但不起作用 print "Hello, would you like to read a file or find whether or not some text

我决定学习如何编程,因为这是每个人首先推荐的,所以我开始编写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
没有定义,但我找不到为什么它没有定义?无论如何,我相信这是显而易见的,但是,嘿,我正在学习,我希望你们中的任何人能告诉我为什么这个代码很糟糕:)

你在
打印
行的上方有一个缺失的偏执狂-

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 -->")

除了另一个答案中缺少的括号外,您在这里还有一个问题:

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编码风格指南。尽管它不会捕获代码中的所有错误。)
  • 尝试使用IDE对代码进行实时反馈;我个人更喜欢
以下是
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

您尚未在此行插入右括号:

    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")

如果您使用的是Python3+,那么print将引发一个错误,因为print的语法是:print(“一些文本”),而遵守PEP8本身不会使代码变得更好。这将使其更易于阅读和调试。:)@Pabtore,没错,但正如你所见,它捕获了阻止OP进展的SyntaxError。