0

Probably very easy, but cant figure it out I just started learning python and the whole programming.

So I have a range of numbers and want to to know how many of those numbers are divisible with 2 or 5 or 7.

Funny as the code shows I can get the sum of those numbers. But how to get the numbers of them?

In this range its 2,4,5,6,7,8,10 so I need the number 7, 7 numbers exist in the range that are ok with the condition.

x=0
for i in range(1,11):
    if i%2 == 0 or i%5 == 0 or i%7==0 :
        x+=i
print(x)
TrebledJ
  • 8,713
  • 7
  • 26
  • 48
PUrba
  • 7
  • 2
  • @Sheldore Some better dupes? https://stackoverflow.com/questions/15375093/python-get-number-of-items-from-listsequence-with-certain-condition / https://stackoverflow.com/questions/1764309/conditional-counting-in-python / https://stackoverflow.com/questions/22904380/count-how-many-values-in-a-list-that-satisfy-certain-condition (I somewhat disagree with "While, if, else counting" being a dupe here.) – TrebledJ Jun 09 '19 at 18:49
  • @TrebledJ : If I reopen, I can't close again but since you posted the links in the comments, the OP can rread them – Sheldore Jun 09 '19 at 19:01
  • @Sheldore Ah, I thought you could edit the dupe list. But ok. ¯\\_(ツ)_/¯ – TrebledJ Jun 09 '19 at 19:02

2 Answers2

2

You're adding the values that comply with your conditions, instead you want to add one to the counter:

x=0
for i in range(1,11):
    if i%2 == 0 or i%5 == 0 or i%7==0 :
        x += 1    # x+= i would add the numbers that are divisible by (2,5,7) to x
print(x)
quamrana
  • 37,849
  • 12
  • 53
  • 71
0

If you want to store the numbers you can add 1 to your variable. If you want to store all the desired occurrences you can append them to an array. Like below:

x = 0
items = []
for i in range(1,11):
    if i%2 == 0 or i%5 == 0 or i%7==0 :
        x+=1 # add one for each correct answer
        items.append(i) # add the correct item
print(x) # 7
print(items) # [2,4,5,6,7,8,10]
Alireza HI
  • 1,873
  • 1
  • 12
  • 20