r/PythonLearning • u/Moral_Roulette34 • 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
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
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 astrobject return byinputto anintobject.
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
forloop 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 alistand check for specific patterns is important.1
u/fllthdcrb Jul 03 '25
Multiple people pointed out the likely reason your
forloop failed, i.e. you must have defined a variable calledrange, which shadowed the built-inrange()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


6
u/D3str0yTh1ngs Jul 02 '25
an integer and a string is not the same thing.
input()returns a string, your list has integers