Python Forum

Full Version: a question from a noob
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Dear All

Shouldn't be the ouput of the program is  below ''1''?? Where do I read wrong?

x = 0
my_list = []
while x < 10:
    if x % 2 == 0:
        my_list.append("dog")
    elif x % 3 == 0:
        my_list.remove("dog")
    x = x + 1
print(my_list.count("dog"))
My comment:
0- do nothing
1- do nothing
2-add dog
3-remove dog
4-add dog
5-do nothing
6-add dog, remove dog
7-do nothing
8- add dog
9-remove dog
Here is what I get:

>>> x = 0
... my_list = []
... while x < 10:
...     if x % 2 == 0:
...         my_list.append("dog")
...     elif x % 3 == 0:
...         my_list.remove("dog")
...     x = x + 1
... print(my_list.count("dog"))
3
yes I know that, output is 3. But I want to understand the path which goes '3'. How can be 3 dogs in my_list. I tried all the 'x'variants in the comment section of my question, as a result I get 1. I am misreading something in it.
Output should be 3, your comment is wrong for x values:
  • 0 - dog is added ( 0 % 2 == 0 )
  • 6 - dog is added, but not removed
if ... elif .. is shortcut for if ... else: if ..., so if first condition is True, second condition is not even evaluated - if statement does not work as "multiple" choices selector. So for 6 dog is only added.

EDIT: if you want to trace my_list changes, put line with print statement on line over your x = x + 1 line - something like print("x = {}, my_list = {}".format(x, my_list))
Thanks. It helped a lot.
Test it! Put print() functions to see what is going on.
>>> x = 0
... my_list = []
... while x < 10:
...     print("x = {}".format(x))
...     if x % 2 == 0:
...         my_list.append("dog")
...         try:
...             print(my_list)
...         except:
...             pass    
...     elif x % 3 == 0:
...         my_list.remove("dog")
...         try:
...            print(my_list)
...         except:
...             pass
...     x = x + 1
... print(my_list.count("dog"))
x = 0
['dog']
x = 1
x = 2
['dog', 'dog']
x = 3
['dog']
x = 4
['dog', 'dog']
x = 5
x = 6
['dog', 'dog', 'dog']
x = 7
x = 8
['dog', 'dog', 'dog', 'dog']
x = 9
['dog', 'dog', 'dog']
3