Home > Software design >  the difference between with and without 'else'
the difference between with and without 'else'

Time:06-13

I'm just start learning Python by myself, before that i have 0 experience in any language. Here's a question I would like to ask you for help:

What's the difference between:

dict_food = {}
for food in ['ham','egg','bacon','egg','egg','egg','bacon','bread','bread']:
if not food in dict_food:
    dict_food[food] = 0
dict_food[food]  = 1

for food, count in dict_food.items():
    print(count, food)

and this:

dict_food = {}
for food in ['ham','egg','bacon','egg','egg','egg','bacon','bread','bread']:
    if not food in dict_food:
        dict_food[food] = 0
    else:
        dict_food[food]  = 1

for food, count in dict_food.items():
    print(count, food)

result for the first one is:

1 ham
4 egg
2 bacon
2 bread

and the second one is:

0 ham
3 egg
1 bacon
1 bread

How dose 'else' works in the second one?

CodePudding user response:

In the first example:

dict_food[food]  = 1

is performed in every iteration, as it is not part of the if-statement - but merely follows it.

In the second example, it is part of the if-statement and is therefore only performed conditionally:

if not food in dict_food:
    dict_food[food] = 0
else:
    dict_food[food]  = 1

CodePudding user response:

On first situation

both code lines will run

dict_food[food] = 1 and dict_food[food] = 0

because it is not part of the if-statement - but merely follows it.

but on second situation

just only a line code run

dict_food[food] = 0 or dict_food[food] = 1

because it is part of the if-statement

  • Related