[Tutor] How to make to exit the loop, while typing Enter

Alan Gauld alan.gauld at freenet.co.uk
Wed Jan 4 13:34:26 CET 2006


Hi John,

The code is looking better, some minor points below:

> import sys
> maxmark = []
> counter = 0
> 
> while 1:
>    try:
>        mark = int(raw_input("Enter the  Values for  the Array: "))
>        maxmark.append(mark)
>        print maxmark
>    except ValueError:
>        #print "From Here to Where "

While what you have written will work, its not usually a good idea 
to use a try/except block to control program flow like that.

In pseudo code terms what you want is:

while more marks
      read and store marks
process marks

So the processing should really be outside the loop.

The idiomatic way to break out of a loop in Python is to 
use the 'break' keyword (it has a cousin 'continue' too)

while:
     try: 
        loop code here
        if loop should end
            break
     except E: 
        handle any exceptions
        either break or continue
post loop processing here

Hopefully that makes sense, it just makes the shape (ie the layout)
of your code follow the logical structure of your design. And it 
doesn't confuse the error handling in the except block with the 
normal 'happy path' process.

>        counter = 0

You already did this up above so its not needed here...

>        length = len(maxmark)
>        max = maxmark[counter]
>        for counter in  range(length):
>                if maxmark[counter] > max:
>                        max = maxmark[counter]

Because you only use counter to access the array you can do 
this more cleanly by using the for syntax directly:

for mark in maxmark:
    if mark > max:
        max = mark

No need for the counter, the length, or the call to range.
I suspect you may have some experience in a language 
like C or Basic or Pascal which doesn't havce a 'foreach' kind 
of operation,  often it can be hard to break out of the idea 
of using indexing to access items in a container. But the for 
loop is designed specifically for that purpose, using 
range() is just a trick to simulate conventional for loops
on the rare occasions when we really do want the 
index.(and the new enumerate() method is reducing 
those occasions even more).

>        print "At last the Maximum Marks U got is  ", max
>        sys.exit()

Because we used break to exit the loop we no longer need 
the sys.exit() call here, nor by implication, the import statement 
at the top.

HTH,

Alan G
Author of the learn to program web tutor
http://www.freenetpages.co.uk/hp/alan.gauld




More information about the Tutor mailing list