Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/298.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 已定义变量名时发生名称错误?_Python_String_Nameerror - Fatal编程技术网

Python 已定义变量名时发生名称错误?

Python 已定义变量名时发生名称错误?,python,string,nameerror,Python,String,Nameerror,每次运行此代码时,都会显示以下错误: 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))

每次运行此代码时,都会显示以下错误:

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

你能指出我做错了什么吗?我认为在第一个if子句中已经定义了最短的_单词。也请不要太咸,我完全是个初学者。提前感谢。

最短的单词将隐藏在您的if范围内。如果您的程序从未输入该If,则它从未定义。我会将shortest_word=放在程序的顶部。

如果您从未输入If的主体,则您从未定义shortest_word。每个变量直到运行时才定义。看起来,在运行时,您的最短单词没有分配。当if采用elif子句或两者都不采用时,您希望将其分配给什么?最短_长度从0开始,并且字符串的长度不能小于0,因此永远不会输入if。我想你需要像shortest_length=floatinf这样的东西,这样它最初被认为比所有东西都大。谢谢。修正了它:
line 46, in <module>
    print('Shortest: %s' % (shortest_word))
NameError: name 'shortest_word' is not defined