我一直在使用Python编写代码,但似乎无法找出错误的位置。如果有人可以提供帮助,或者提供一些提示让我朝着正确的方向前进,那将非常感激。
def find_longest_word(a):
length = len(a[0])
word = a[0]
for i in wordlist:
if len(i) > length:
word = (i)
length = len(i)
return word, length
def main():
wordlist = input("Enter a few words and I will find the longest: ").split()
word, length = find_longest_word(wordlist)
print (word,"is the longest word that you have listed.")
main()
答案 0 :(得分:3)
find_longest_word
函数wordlist
未定义。我们需要在a
循环中使用变量for
。从for i in wordlist:
更改为for i in a:
raw_input()
。代码:
def find_longest_word(a):
length = len(a[0])
word = a[0]
for i in a:
if len(i) > length:
word = i
length = len(i)
return word, length
def main():
wordlist = raw_input("Enter a few words and I will find the longest: ").split()
word, length = find_longest_word(wordlist)
print (word,"is the longest word that you have listed.")
main()
输出:
vivek@vivek:~/Desktop/stackoverflow$ python 23.py
Enter a few words and I will find the longest: 1 234 2344 3 4
('2344', 'is the longest word that you have listed.')
使用集合模块和字典方法。
>>> import collections
>>> msg = "whish word is longest from this msg"
>>> msg.split()
['whish', 'word', 'is', 'longest', 'from', 'this', 'msg']
>>> d = collections.defaultdict(list)
>>> for i in msg.split():
... d[len(i)].append(i)
...
>>> d
defaultdict(<type 'list'>, {2: ['is'], 3: ['msg'], 4: ['word', 'from', 'this'], 5: ['whish'], 7: ['longest']})
>>> max(d.keys())
7
>>> d[max(d.keys())]
['longest']
>>>
答案 1 :(得分:0)
您的缩进必须是四个空格或功能下的标签,并且必须在整个程序中保持一致。
def find_longest_word(a):
length = len(a[0])
word = a[0]
for i in a:
if len(i) > length:
word = (i)
length = len(i)
return word, length
def main():
wordlist = raw_input("Enter a few words and I will find the longest: ").split(' ')
word, length = find_longest_word(wordlist)
print(word,"is the longest word that you have listed.")
main()
答案 2 :(得分:0)
Python 缩进敏感!
Python期望:
之后的代码块。定义的结束由比当前缩进更小的缩进确定。
与C系列不同,Python没有{}
来确定块的开始或结束位置。
您的代码应如下所示:
def find_longest_word(a):
length = len(a[0])
word = a[0]
for i in wordlist:
if len(i) > length:
word = (i)
length = len(i)
return word, length
def main(): #EXPECTS INDENTATION
#CODE INSIDE THE INDENTED CODE BLOCK WILL BE EXECUTED
#ONLY IF FUNCTION main() IS CALLED
wordlist = input("Enter a few words and I will find the longest: ").split()
word, length = find_longest_word(wordlist)
print (word,"is the longest word that you have listed.")
#END OF INDENTATION MARKS THE END OF A CODE BLOCK
#THIS MEANS main() WILL GET CALLED EVERYTIME YOU
#START THIS PROGRAM IN IDLE
main()
除此之外,您的代码中还会出现一些逻辑错误,这些错误也会导致错误。