[Tutor] SEE THE QUESTION AT THE BOTTOM

Steven D'Aprano steve at pearwood.info
Sat Feb 4 13:09:48 CET 2012


Debashish Saha wrote:
> INPUT:
> 
> 
> 
> *for n in range(2, 1000):*
> 
> *    for x in range(2, n):*
> 
> *        if n % x == 0:*


Please don't add junk characters to your code. There is no need to add 
asterisks to each line, we can recognise Python code when we see it. Your code 
cannot run because of the junk added to the start and end of each line.

[...]

>                                             :QUESTION:
> 
> BUT I COULD NOT UNDERSTAND HOW THE COMMAND ELSE CAN WORK,THOUGH IT IS IN
> THE OUTSIDE OF THE FOR LOOP IN WHICH IF COMMAND LIES.

Please do not SHOUT in ALL CAPITALS, it is considered rude.

In Python, "else" is not just for "if" statements:


if condition:
     do_true_condition
else:
     do_false_condition


Python also has "else" for for-loops and while-loops:


for x in sequence:
     ...
else:
     # this part runs after the for loop is done


while condition:
     ...
else:
     # this part runs after the while loop is done


In both cases, "break" inside the loop will skip past the "else" block without 
executing it.


Try blocks also have an else:


try:
     ...
except TypeError:
     # code that runs if TypeError occurs
except ValueError:
     # code that runs if ValueError occurs
else:
     # code that runs if no error occurs
finally:
     # code that runs no matter what


See the tutorial:

http://docs.python.org/tutorial/controlflow.html

Start here:

http://docs.python.org/tutorial/index.html

(Although the site seems to be done just at the moment.)



-- 
Steven


More information about the Tutor mailing list