BigO
BigO

Reputation: 364

Iterating through an integer in python using a For Loop, Logic Error

Hello I am trying to iterate through a integer and print out its ranges based of 50. I have managed to complete the task but it only works for numbers that are NOT evenly divisible by 50. See examples below. I know my logic is incorrect somewhere, any help seeing where it is incorrect would be appriciated.

Code:

catNum = 244
rangeNum = catNum
counter =0 
for i in range(catNum):
   
    if(counter != 0):
      catNum = rangeNum
      catNum = catNum -1

    rangeNum = rangeNum - 50

    if(rangeNum < 0):
        rangeNum = 0 
        rangeSet = ("%s-%s"%(rangeNum, catNum ))
        print(rangeSet)
        break 
    
    counter +=1
    rangeSet = ("%s-%s"%(rangeNum, catNum ))
    print(rangeSet)

Output:(correct)

194-244
144-143
94-93
44-43
0-43

But if catNum is divisible by 50 evenly for example 300 Output:(incorrect)

250-300
200-249
150-199
100-149
50-99
0-49
0--1

Expected:

250-300
200-249
150-199
100-149
50-99
0-49

Any help seeing where my logic is incorrect would be appreciated

Upvotes: 0

Views: 49

Answers (1)

Shoaib Mirzaei
Shoaib Mirzaei

Reputation: 522

catNum is negative too. you should add a condition for catNum too. use below code

catNum = 300
rangeNum = catNum
counter =0 
for i in range(catNum):
    if(counter != 0):
      catNum = rangeNum -1

    rangeNum = rangeNum - 50
    if(rangeNum < 0):
        if catNum <= 0:
            break
        rangeNum = 0 
        rangeSet = ("%s-%s"%(rangeNum, catNum ))
        print(rangeSet)
        break 
    else:
        counter +=1
        print( "%s-%s"%(rangeNum, catNum ) )

Upvotes: 2

Related Questions