Forums: » Register « |  Free Tools |  User CP |  Games |  Calendar |  Members |  FAQs |  Sitemap |  Support |

New Free Tools on Dev Shed!

#1
April 12th, 2013, 10:23 AM
 russ123
Registered User

Join Date: Nov 2012
Posts: 19
Time spent in forums: 8 h 21 m 37 sec
Reputation 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
April 12th, 2013, 10:48 AM
 Nyktos
Contributing User

Join Date: Dec 2012
Posts: 114
Time spent in forums: 1 Day 11 h 54 m 6 sec
Reputation 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.

#3
April 12th, 2013, 11:32 AM
 b49P23TIvg
Contributing User

Join Date: Aug 2011
Posts: 4,165
Time spent in forums: 1 Month 3 Weeks 2 Days 9 h 34 m 16 sec
Reputation Power: 455
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!

#4
April 12th, 2013, 01:27 PM
 b49P23TIvg
Contributing User

Join Date: Aug 2011
Posts: 4,165
Time spent in forums: 1 Month 3 Weeks 2 Days 9 h 34 m 16 sec
Reputation Power: 455
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'

#5
April 13th, 2013, 05:52 AM
 russ123
Registered User

Join Date: Nov 2012
Posts: 19
Time spent in forums: 8 h 21 m 37 sec
Reputation Power: 0
Quote:
 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!

 Viewing: Dev Shed Forums > Programming Languages > Python Programming > Using a for loop to set a variable implicitly. Is this acceptable?