Coding problem with if and else statement in the code. cannot understand

hi i cant understand the following code

arr = input("Please enter text: ")
n = len(arr)
count=0
elements_count = {}

iterating over the elements for frequency

for element in arr:

> if element in elements_count:
>     	elements_count[element] += 1
>     else:
>         elements_count[element] = 1

for key, value in elements_count.items():
print(f"{key}: {value}")

the result is
Please enter text: abcdabc
a: 2
b: 2
c: 2
d: 1

In order for your code to be readable on this forum, you should put your code between triple ticks like:

```
print(a)
```

Secondly, we need more than just “I can’t understand this code”. What is it that you are trying to do? What parts do you understand? What do you expect to happen? Where is the code from? I assume you didn’t write it yourself?

I’ve added comments to the code. Hope it helps.

#arr = input("Please enter text: ") # Get string
arr = 'Test String aaaaaa bbbbbbbbb ccc' # Test string I used.
n = len(arr) # get length ol string not used
count=0 # Not used
elements_count = {} # create empty dictionary or maping

for element in arr: # Loop over characters in string, use as key for dict.
    print(F'Found "{element}"') # Print each element
    if element in elements_count: # Is key in dictionary
        elements_count[element] += 1 # add 1 to dictionary element if yes
    else: # Not in dictionary
        elements_count[element] = 1 # set element to 1 to start counnter at 1

for key, value in elements_count.items(): # Now get key and value
    print(f"'{key:3}': {value:3}") # print result
1 Like

Hi. Thanks for the reply. really helpful, loved it. But I have a problem with this line if element in elements_count: # Is key in dictionary. Isnt the elements_count empty. Sorry for asking a noob question but I would really appreciate your help. Thankyou so much.

Isnt the elements_count empty.

It’s only empty for the first iteration of the loop.

for element in arr is a loop that will repeat the logic of:

if element in elements_count: # Is key in dictionary
        elements_count[element] += 1 # add 1 to dictionary element if yes
    else: # Not in dictionary
        elements_count[element] = 1 # set element to 1 to start counnter at 1

In the first iteration, elements_count is empty, therefore it will execute the else path, which is

elements_count[element] = 1 

So after that first iteration, elements_count contains one element.

At the next iteration element in elements_count is not empty and could return True.

1 Like

this makes so much sense now. thankyou so much. can you recommend any good books that have these kind of basic fundamental issues of python explained just like you did. thankyou so much for your help.