NameError while variable name is already defined?

NameError while variable name is already defined?

import random

n = random.randint(3,6)
print("I'll need %s words: " % (n))

a = 1
shortest_length = 0
longest_length = 0
total_length = 0


for i in range (n) :
    word = input("Word #%a please > " % (a))
    total_length += len(word)
    a+=1
    
    #finding the shortest word
    if shortest_length > len(word):
        shortest_length = len(word)             
        shortest_word = word
            
    #finding the longest word
    elif longest_length < len(word):
        longest_length = len(word)
        longest_word = word

average = format(total_length/n, '.2f')

print('Shortest: %s' % (shortest_word))
print('Longest: %s' % (longest_word))
print('Average Length: %s' % (average))

每次我 运行 这段代码都会显示这个错误:

line 46, in <module>
    print('Shortest: %s' % (shortest_word))
NameError: name 'shortest_word' is not defined

你能指出我这里做错了什么吗?我认为 shortest_word 已经在第一个 if 子句中定义了。另外请不要太咸我是一个初学者。提前致谢。

shortest_word 埋在你的 if-scope 里。如果你的程序从不输入那个 if,它就永远不会被定义。我会把 shortest_word = " " 放在程序的顶部。