pythonhelp d s banana for letter in s if letter not in d

#pythonhelp

d = {}

s = \'banana\'

for letter in s:

      if letter not in d:

            d[letter] = \'odd\'

      elif d[letter] == \'even\':

            d[letter] = \'odd\'

      else:

           d[letter] = \'even\'

print(d)

#answer = {\'n\': \'even\', \'b\': \'odd\', \'a\': \'odd\'}. Please explain how this is the answer and dictionary is very confusing so please explain all the lines.

Solution

here is the output for each iterationof the loop

{\'b\': \'odd\'}                                                                                                                                                                    

{\'a\': \'odd\', \'b\': \'odd\'}                                                                                                                                                        

{\'a\': \'odd\', \'b\': \'odd\', \'n\': \'odd\'}                                                                                                                                            

{\'a\': \'even\', \'b\': \'odd\', \'n\': \'odd\'}                                                                                                                                           

{\'a\': \'even\', \'b\': \'odd\', \'n\': \'even\'}                                                                                                                                          

{\'a\': \'odd\', \'b\': \'odd\', \'n\': \'even\'}                                                                                                                                           

{\'a\': \'odd\', \'b\': \'odd\', \'n\': \'even\'}

so finally the output for the last iteration is {\'a\': \'odd\', \'b\': \'odd\', \'n\': \'even\'}

so when we are printing \"d\" by comming out of the for loop we get the awnser as {\'a\': \'odd\', \'b\': \'odd\', \'n\': \'even\'}

#pythonhelp d = {} s = \'banana\' for letter in s: if letter not in d: d[letter] = \'odd\' elif d[letter] == \'even\': d[letter] = \'odd\' else: d[letter] = \'e

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site