r/PythonLearning • • Jul 02 '25

[help needed] counter not working?

i dont see why it says the target appears 0 times if target = 1 and 1 appears once in the list

1 Upvotes

11 comments sorted by

6

u/D3str0yTh1ngs Jul 02 '25

an integer and a string is not the same thing. input() returns a string, your list has integers

2

u/ninhaomah Jul 02 '25

1

u/Moral_Roulette34 Jul 02 '25

yes, I tried using for i in range and now I'm trying a while loop instead

2

u/Darkstar_111 Jul 02 '25

Gotta Intify that input.

2

u/Moral_Roulette34 Jul 02 '25

yep that was it, cheers

2

u/FoolsSeldom Jul 02 '25 edited Jul 02 '25

Are you sure you are comparing the same kind of objects? Example solution below.

NB. As you haven't shared the code for the population of the list, I've included a simple line to gather that information. Key is the conversion all cases of a str object return by input to an int object.

numbers = [int(input(f"#{n:2}: ")) for n in range(1, 11)]
target = int(input("Target: "))
target_count = 0
count = 0
while count < 10:
    if numbers[count] == target:
        target_count += 1
    count += 1
print(f"{target} was found {target_count} times")

PS. Why are you not using a for loop?

1

u/Moral_Roulette34 Jul 02 '25

yeah i just needed to convert the input for target to an integer. tried with a for loop and got an error message so switched to a while loop instead.

2

u/FoolsSeldom Jul 02 '25

Worth trying a for loop again now. Basically, for num in numbers:

It is good to learn the basics of loops. For future reference, not that you can do this in a much easier way, target_count = numbers.count(target), but there are plenty of other situations where there isn't an easy shortcut so learning how to walk through a list and check for specific patterns is important.

1

u/fllthdcrb Jul 03 '25

Multiple people pointed out the likely reason your for loop failed, i.e. you must have defined a variable called range, which shadowed the built-in range() function you were trying to use. All you had to do was rename that variable.

Perhaps it was worth moving away from that, so you could find this other problem. But it's still worth learning what you should and should not do, as well as how to diagnose and fix problems like that. In my opinion, it's not good to get into the habit of just leaving such a variable like that, unless you know what you're doing and can live with the consequences.

1

u/Refwah Jul 02 '25

for number in numbers: