user5537461
user5537461

Reputation: 1

Skipping For loop in Python

Inside my code it has been skipping the for iteration Heres the code i have been using

 print ("part two")
varZ = varA - 0.5
varY = firstNumber / varZ

for varZ in list(reversed(range(firstNumber, 0))):
    print ("part three")
    varY = firstNumber / varZ
    if (varY - int(varY) == 0):
        print ("part four")
        break

    else:
        varZ = varZ - 1
        print ("part five")

print("Part six, Your answer is...", int(varZ))

Thanks for the help! P.s the output is

Your number sir? 27
Calculating...
13.5
part two
Part six, Your answer is... 13

Upvotes: 0

Views: 43

Answers (2)

Tom Karzes
Tom Karzes

Reputation: 24052

range(firstNumber, 0) is going to be an empty list (unless firstNumber is negative). The default increment is 1. If you get rid of the 0, then the range expression will count up from 0 to firstNumber-1. I'm not sure if you want to start with firstNumber or firstNumber-1, so I'll use n in this example:

for x in list(reversed(range(n))):

You can simplify this to:

for x in reversed(range(n)):

or just:

for x in range(n-1, -1, -1):

These will all count down from n-1 to 0, inclusive.

If you're using Python 2, you can use xrange in place of range to avoid actually constructing the list. In Python 3 you can just use range.

Upvotes: 0

George
George

Reputation: 2093

range(firstNumber, 0) is almost certainly empty, unless you're expecting a negative firstNumber. It's unclear what you're trying to do here; if you're trying to iterate over something like [5,4,3,2,1,0], you should use range(5, 0, -1). Read the docs for more info

Upvotes: 1

Related Questions