这段代码中globals()的用途是什么?

时间:2018-09-26 04:13:00

标签: python python-3.x dictionary global-variables

d={}
for x in range(5):
        globals()['int%s' % x] = int(input("Enter the marks of the students: "))
a = int0 + int1 + int2 + int3 + int4
print ("The average marks are ", a/5)

我不理解此代码中字典globals()['int%s' % x]的使用。我是Python的新手,也是一般的编程人员,所以如果有人可以用非常简单的语言回答这个问题,将不胜感激。

非常感谢您。

1 个答案:

答案 0 :(得分:0)

别担心,这是学习我所见到的任何语言的最糟糕,最糟糕的代码……我的意思是,如果您正在学习第一个原理,那么现在不要太长时间看它。当您获得更多练习时,请复习一下。那只是一个建议。无论如何,我会逐行向您解释:

d={}

'''
here declares a variable with name d, and saves an empty dictionary to it... 
I don't know why, because it is never used
'''

for x in range(5):
    globals()['int%s' % x] = int(input("Enter the marks of the students: "))

'''
this is a loop that will be repeated 5 times, globals() is a dictionary 
of all the variables in the scope that are alive with in the program... 
so, globals()['int%s' % x] is creating a new key-value,
for example {'int0': 4}. It is a way to dynamically create variables, so, 
the x will have the values [0,1,2,3,4], that's why the variables
will have the names int0, int1, int2, int3, int4.
Finally, it ask to the user to type a number, 
and this number will be stored in one of those variables, 
then the maths:
'''


a = int0 + int1 + int2 + int3 + int4
'''sum all the inputs from the user'''
print ("The average marks are ", a/5) 
#divide it by 5
  

一种实现相同目的的可能方法,但更笼统一点:

total=0
numberOfMarks = 5
for x in range(numberOfMarks):
  mark = input("Enter the marks of the students: ")
  while(not mark or not mark.isdigit()):
    print("please, enter a number value representin the mark")
    mark = (input("Enter the marks of the students: "))

  total += int(mark)

print ("The average marks are ", total/numberOfMarks)