Python Forum

Full Version: Occurrences using FOR and IF cycle
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hello everyone,

I am trying to find the number of times that a certain value appears in a string like [100, 100, 50, 20, 100, 30]. The user should insert a number (e.g. 100) and the program will give the answer (e.g. 3). I know how to do this using Count but I would like to solve the problem by simly using cyclic instruction like FOR and IF. Unfoltunately my code does not work. Do you have any idea on how to make this work? Thank you
a = [100, 100, 50, 20, 100, 30]
x = input("Insert number: ")
c = 0
for i in range(len(a)):
    if x == a[i]:
        c = c + 1
print(c)
1. Don't use range(len(a)), python cycle iterates over values, not indexes, just write
for item in a:
2. Your code works well
a = [100, 100, 50, 20, 100, 30]
x = 100
c = 0
for i in range(len(a)):
    if x == a[i]:
        c = c + 1

print(c)
>>> 3
3. Better code
a = [100, 100, 50, 20, 100, 30]
x = 100
c = sum(1 for i in a if i == x)

print(c)
(Jul-29-2019, 01:21 PM)fishhook Wrote: [ -> ]2. Your code works well
a = [100, 100, 50, 20, 100, 30]
x = 100
c = 0
for i in range(len(a)):
    if x == a[i]:
        c = c + 1

print(c)
>>> 3
YOUR code works well because you replaced the x = input("Insert number: ") with x = 100.
HIS code doesn´t work because the input function returns a string and not an integer value.
So the code must be edited into x = int(input("Insert number: "))