简体   繁体   中英

How do I get a for loop to iterate through an entire range?

Suppose I have a for loop such as this:

a = 15
for x in range(2,6):
    if a % x == 0:
        return False
    return True

How can I get the for loop to check all values in the assigned range before returning true/false? Right now it just checks 2, hence 15%2 = true. I want the loop to check 2, 3, 4, and 5 and then return true/false based on the conditions.

add a boolean variable and return that instead

check = True
a = 15
for x in range(2,6):
    if a % x == 0:
        check = False
return check

by the looks of it, you can achieve what you want with an all statement, or just returning True outside of the for loop:

a = 15
return all(a%x!=0 for x in range(2,6))

#or

a = 15
for x in range(2,6):
    if a%x== 0: return False
return True

Take the return True out of the loop.

a = 15
for x in range(2,6):
    if a % x == 0:
        return False
return True

This will return true iff a is not divisible by any number in the 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