简体   繁体   中英

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! Ps the output is

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

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

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM