#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Nov 2012
    Posts
    19
    Rep Power
    0

    Using a for loop to set a variable implicitly. Is this acceptable?


    ... and would it work reliably?
    Code:
    for x in range(100, 200):
        if x % 7 == 0:
            break
    print x, 'is the first multiple of 7 from 100 upwards'
  2. #2
  3. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Dec 2012
    Posts
    114
    Rep Power
    3
    It certainly works, and is supposed to. It's liable to confuse some people but there isn't really a better way to do it.
  4. #3
  5. Contributing User
    Devshed Demi-God (4500 - 4999 posts)

    Join Date
    Aug 2011
    Posts
    4,889
    Rep Power
    481
    Code:
    # poor, and inefficient
    for x in range(100, 200):
        if x % 201 == 0:
            break
    
    print x, 'is the first multiple of 201 from 100 upwards'
    
    
    
    # this seems reliable and more efficient
    n, a = 100, 201
    if n % a:
        x = (1+n//a)*a
    else:
        x = n
    
    print('{} is the first multiple of {} from {} upwards'.format(x, a, n))
    [code]Code tags[/code] are essential for python code and Makefiles!
  6. #4
  7. Contributing User
    Devshed Demi-God (4500 - 4999 posts)

    Join Date
    Aug 2011
    Posts
    4,889
    Rep Power
    481
    And, if you must use the loop, write thusly:
    Code:
    for x in range(100, 100+7):### from 100 to 100+ the divisor
        if x % 7 == 0:
            break
    
    print x, 'is the first multiple of 7 from 100 upwards'
    [code]Code tags[/code] are essential for python code and Makefiles!
  8. #5
  9. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Nov 2012
    Posts
    19
    Rep Power
    0
    Originally Posted by b49P23TIvg
    And, if you must use the loop, write thusly:
    Code:
    for x in range(100, 100+7):### from 100 to 100+ the divisor
        if x % 7 == 0:
            break
    
    print x, 'is the first multiple of 7 from 100 upwards'
    That's why I love this forum

    I was really just talking about what was mentioned in the title but you answered that too, and more, thanks!

IMN logo majestic logo threadwatch logo seochat tools logo