+ 2

Can anyone explain please?

Found this question in a challenge but can't understand the for cycle: What is the output of this code? a = {0:1, 1:2) _sum =0 for b in a: _sum += b print(_sum + b) Thanks!

4th Feb 2020, 12:56 PM
Raffaele
Raffaele - avatar
4 Answers
+ 4
Python, I assume? a for loop looping over a dictionary (a) is actually looping over the keys. So b will be first 0, then 1. Also in Python, the loop variable behaves like a regular variable, so it stays at the value it had last - which is 1. So if you add 0+1+1, the result is 2. There's a typo: The dictionary should end with }. You might wand to find a more specific title for the question. And can you maybe add tags to help other users finding it if need be? Could be for example 'Python' and 'challenge'.
4th Feb 2020, 2:52 PM
HonFu
HonFu - avatar
+ 2
Thanks HonFu! And what if I wanted to cycle through the values of the dictionary instead? Sorry for the format of the question-still trying to figure out how it all works!
4th Feb 2020, 11:47 PM
Raffaele
Raffaele - avatar
+ 2
You can use: for b in a.values(): ... Or let's say, you wanted to add the values to _sum, you could use the same loop as before but write: for b in a: _sum += a[b]
4th Feb 2020, 11:51 PM
HonFu
HonFu - avatar
+ 1
Which language?
4th Feb 2020, 1:36 PM
Yasser Arce
Yasser Arce - avatar