我决定学习编程,因为这是每个人都首先推荐的,所以我已经开始研究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上找不到任何东西。另外,如果我像我说的那样标记出可变行,但是在运行它(运行该elif
部分)时键入“ find”,则会收到一条错误消息,指出findname
未定义,但我找不到为什么不行?无论如何,我敢肯定这是显而易见的,但是,嘿,我正在学习,我很想知道你们中的任何一个告诉我为什么这段代码很烂:)
除了其他答案指出的缺少括号外,您在这里还有一个问题:
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。尽管它不会捕获代码中的所有错误。)以下是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
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句