Python Forum

Full Version: Help debugging the code
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hey! I have a home task that i cant do. I'm fairly new to python and this is quite difficult for me. Will appreciate any help:

If the function is called in the following way: print_list([1, '2', 3, '4']), then the output should be like this:

Output:
2 0 4
def print_list(some_list):

    while i < range(len(some_list)):
        if some_list[i] % 2 == 0:
            print(some_list[i])
        if some_list[i] % 3 == 0:
            print(some_list[i] % 3)
        i += 1
From what I understand i need to use For loop
Yes a for loop will work.
List of suggested links to help:

python types
python variables
python for loops
python list
Hi @cheburashka welcome to the forum,
You know there is a "homework" section in this forum? You had better post it there.
You already created a function and a while loop and if- statements. You did that right. But he logic is not. Let me help you.
while i < range(len(some_list)):
Here you are mingling a lot of things, and not in the correct way. You are comparing "i" with a range. Obviously "i" represents an integer. So you should compare it with an integer. Not a range. And you did not assign a value before using it. Probably you meant to do something like this:
i = 0
while i < len(some_list):
Though syntactically correct, it is not the best way to do this. Use the best structure to fit your needs:
for element in some_list:
"element" will contain in turn each element of the list.

Then there is a problem in the given list: some of the elements are integers, some are strings. You cannot calculate with strings. So you will have to convert the strings to integers. You can do this with the int() function. It does no harm to use int() on an integer, so you can do:
if int(element) % 2 == 0:  # Only even numbers.
    print(element)
And you will have to explain the logic why from the list [1, '2', 3, '4'] only [2, 0, 4] have to be printed.

Please show us what your new code and what the output and errors are (enclosed in the correct tags).
Thank you for your help! Now i know about the homework section.

The solution turned out to be quite easy:

def print_list(some_list):
    
    i = 0
    while i in range(len(some_list)):
        if int(some_list[i]) % 2 == 0:
            print(some_list[i])
        if int(some_list[i]) % 3 == 0:
            print(some_list[i] % 3)
        i += 1
Another way of doing it

def print_list(some_list):
    for n in some_list:
        n = int(n)
        if n % 2 == 0:
            print(n)
        if n % 3 == 0:
            print(0)

print_list([1,'2',3,'4'])
Output:
2 0 4