+ 10

Python programming question n.1

confusion={} confusion[1]=1 confusion['1']=2 confusion[1]+=1 sum=0 for k in confusion: sum+=confusion[k] print(sum) What does k mean in this program and why is the answer 4? Thank you 🌸

25th Dec 2018, 6:45 AM
Eros boulay
Eros boulay - avatar
7 Réponses
+ 15
Here a dictionary is created if name confusion Second line-{1:1} Third line-{1:1,'1':2} Fourth line-{1:2,'1':2} After that k refers to all the keys present in the dictionary I.e. 1,'1' Hence, confusion[k] refers to all the values of the dictionary So, it sums all the values of dictionary is 2+2=4
25th Dec 2018, 7:03 AM
Pulkit Kamboj
Pulkit Kamboj - avatar
+ 3
Tyrant, the code is quite fine. Confusion is a dictionary here. (Although "sum" is not a very good variable name, as it's also a built-in function.)
25th Dec 2018, 7:04 AM
Kishalaya Saha
Kishalaya Saha - avatar
+ 3
Thank you all ,especially Pulkit Kamboj,your explanation is very clear.
25th Dec 2018, 7:08 AM
Eros boulay
Eros boulay - avatar
+ 2
I think you wrote the whole thing wrong...this is what i think you meant.. confusion={} confusion.append(1) confusion.append(2) confusion[1]+=1 sum=0 for k in confusion: sum+=k print(sum) K is a holder variable,it refers to a value in a container('confusion'),It keeps on changing till it reaches the end of the container... All of this is covered in the python tutorial in the app....
25th Dec 2018, 6:59 AM
Mensch
Mensch - avatar
+ 1
Thank you 🍰 Merry Christmas
25th Dec 2018, 7:04 AM
Eros boulay
Eros boulay - avatar
0
a for loop is a control structure to iterate through things like = list, tuples, string, dicts, sets ... But not in integers ... In this case you built up a dicitionary which contains: confusion = { 1: 2, '1': 2, } # variable sum set to 0 sum = 0 And with the for loop: for k in confusion: sum += confusion[k] # when you iterate through a dict # you iterate on its keys, in this # case 1 and '1' so when you say # sum += confusion[k] is like: # sum += confusion [1] And the value of the key 1 is 2 # sum += confusion['1' And the value of the key '1' is 2 # so the for loop will sum those values to the variable sum... print(sum)
25th Dec 2018, 9:30 PM
Edwing123
Edwing123 - avatar
0
when you use for loop, all the numbers will be iterated through. And when you combine "sum=0" with numbers that are iterated together, it will gives you the number 4(0+1+2+1).That's what I think he he:))
27th Dec 2018, 12:07 AM
Khai123
Khai123 - avatar