Problem with following python code
Gabriel Genellina
gagsl-py2 at yahoo.com.ar
Tue Jun 12 00:57:57 EDT 2007
En Tue, 12 Jun 2007 01:25:31 -0300, why? <jimbomaan at yahoo.com> escribió:
> I've been having problem with the following code. It's supposed to
> print the prime numbers between 10 and 100. But i'm not getting any
> output, i.e. i guess the outer 'for' loop is being traversed only
> once. I would be greatful if you could help me out. Thanx!
>>>> f=1
>>>> for i in range(10,100):
> ... for j in range(2,i):
> ... if i%j==0:
> ... f=0
> ... break
> ... else: continue
> ... if f==1:
> ... print i,
> ...
>
Note that once you set f=0, it will never change.
Move the f=1 inside the outer loop. Also, the else clause is useless here;
best to use a bool for conditions; and it would benefit from better
variable names. Keeping the same structure:
for number in range(10,100):
is_prime = True
for divisor in range(2,number):
if number % divisor == 0:
is_prime = False
break
if is_prime:
print number,
Next step: for loops have an optional "else" clause, that gets executed
whenever the loop exits normally (in this case, when divisor goes up to
number, and the break statement is never executed). So you don't need
is_prime:
for number in range(10,100):
for divisor in range(2,number):
if number % divisor == 0:
break
else:
print number,
--
Gabriel Genellina
More information about the Python-list
mailing list