【问题标题】:NameError while variable name is already defined?NameError,而变量名已经定义?
【发布时间】:2020-10-16 15:54:07
【问题描述】:
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 子句中定义了。另外请不要太咸,我是一个初学者。提前致谢。

【问题讨论】:

  • 如果你从不输入if的正文,你就永远不会定义shortest_word
  • 每个变量直到运行时才被定义。看起来,在运行时,您的 shortest_word 未分配。当if 使用elif 子句或两者都不使用时,您希望它分配给什么?
  • shortest_length从0开始,字符串的长度永远不能小于0,这样if就永远不会被输入。我想你想要像shortest_length = float("inf") 这样的东西,所以它最初被认为比一切都大。
  • 谢谢。修复它:)

标签: python string nameerror


【解决方案1】:

shortest_word 隐藏在您的 if 范围内。如果您的程序从不输入 if,则它永远不会被定义。我会将 shortest_word = " " 放在程序的顶部。

【讨论】:

    猜你喜欢
    • 2022-11-18
    • 1970-01-01
    • 2021-09-13
    • 1970-01-01
    • 1970-01-01
    • 2017-08-30
    • 2022-01-10
    • 2012-02-20
    相关资源
    最近更新 更多