Python Forum
Occurrences using FOR and IF cycle
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Occurrences using FOR and IF cycle
#1
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)
Reply
#2
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)
Reply
#3
(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: "))
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Need to fix SyntaxError in cycle try alexfrol86 14 3,138 Mar-27-2022, 07:53 AM
Last Post: stevendaprano
  Count number of occurrences of list items in list of tuples t4keheart 1 2,367 Nov-03-2020, 05:37 AM
Last Post: deanhystad
  Trying to cycle through a list of charcters pooky2483 12 4,433 Sep-28-2020, 06:55 AM
Last Post: pooky2483
  Count & Sort occurrences of text in a file oradba4u 7 3,066 Sep-06-2020, 03:23 PM
Last Post: oradba4u
  <while> cycle is not interrupted when using the <random>module ShityCoder 3 2,154 Sep-04-2020, 04:05 PM
Last Post: ShityCoder
  Cycle of numpy variables Zero01 0 1,548 Jul-31-2020, 11:58 AM
Last Post: Zero01
  stop cycle while windows11 1 2,000 May-16-2020, 03:17 PM
Last Post: deanhystad
  Counting number of occurrences of a single digit in a list python_newbie09 12 5,477 Aug-12-2019, 01:31 PM
Last Post: perfringo
  pool map cycle skorost5 5 3,803 Apr-07-2019, 09:21 AM
Last Post: skorost5
  Printing Easter date occurrences samsonite 8 4,989 Mar-06-2019, 11:49 AM
Last Post: samsonite

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020