Search code examples
pythonstringnameerror

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

Everytime I run this code it shows this error:

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

Can you point out what I did wrong here? I thought shortest_word is already defined inside the first if clause. Also pls don't be salty I'm a total beginner. Thanks in advance.


Solution

  • shortest_word is buried in your if-scope. If your program never enters that if, it's never defined. I would put shortest_word = " " at the top of your program.