I'm trying to understand following python code as I'm new to it.
import random
howMany = random.randint(0,1000)
stats = {}
for i in range(howMany):
value = random.randint(0,500)
stats.setdefault(value,0)
stats[value]+=1
for item in stats:
if stats[item] > 1:
print item
Here is what I have understood so far, my questions will follow afterwards:
howManystores the random number generated between 0 & 1000 inclusive of both.stats = {}declares an empty dictionaryiwill run depending upon the value ofhowMany. For example ifhowManywas 2 soiwill run for two times with values is0and1.valuevariable stores random number between0&500inclusive of bothI didn't understand
stats.setdefault(value,0). For example, thevaluevariable has value4, thenstats.setdefault(4,0)means what?What does
stats[value]+=1do? The expanded form ofstats[value]+=1isstats[value] = value + 1?I understood the following paragraph:
for item in stats: if stats[item] > 1: print itemThose values are printed which are greater than
1in thestatsdictionary. Please correct me if I'm wrong somewhere.