John SoBell
John SoBell

Reputation: 15

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.

Upvotes: 0

Views: 202

Answers (3)

R Nar
R Nar

Reputation: 5515

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

Upvotes: 3

andars
andars

Reputation: 1404

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.

Upvotes: 2

Darendal
Darendal

Reputation: 863

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

Upvotes: 3

Related Questions