这是我在Python Run Command中获得的错误代码,我尝试了多种方法来解决这个问题。任何人都可以指出我做错了什么以及如何解决它?
Traceback (most recent call last):
File "J:\Python\SumOfNumbers.py", line 24, in <module>
main ()
File "J:\Python\SumOfNumbers.py", line 15, in main
total += float(num)
NameError: global name 'num' is not defined
def main ():
# Declare varibles
line = ''
total = 0.0
number = 0.0
#Open numbers.txt file and make sure that numbers.txt is in the same
#folder as Python.
infile = open('numbers.txt', 'r')
for line in infile:
number= float(line)
total += float(num)
# Close file
infile.close ()
# Display the total of the numbers in the file
print ('Total: ', total)
# Call the main function.
main ()
答案 0 :(得分:0)
在你的代码中,你写了
total += float(num)
但是,num不是变量的名称。你应该写的
total += float(number)
答案 1 :(得分:0)
你走了。名为num的变量未初始化,在您的程序中它被称为数字。当python使用它们来定义代码块时,请注意缩进。
def main():
line = ''
total = 0.0
number = 0.0
# Open numbers.txt file and make sure that numbers.txt is in the same
# folder as Python.
infile = open('numbers.txt', 'r')
for line in infile:
number = float(line)
total += float(number)
# Close file
infile.close()
# Display the total of the numbers in the file
print ('Total: ', total)
# Call the main function.
main()