a question from a noob - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: a question from a noob (/thread-2397.html) |
a question from a noob - kompressano - Mar-13-2017 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 RE: a question from a noob - wavic - Mar-13-2017 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 RE: a question from a noob - kompressano - Mar-13-2017 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. RE: a question from a noob - zivoni - Mar-13-2017 Output should be 3, your comment is wrong for x values:
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))
RE: a question from a noob - kompressano - Mar-13-2017 Thanks. It helped a lot. RE: a question from a noob - wavic - Mar-13-2017 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 |