[Tutor] help
Danny Yoo
dyoo@hkn.eecs.berkeley.edu
Tue, 2 Oct 2001 11:55:12 -0700 (PDT)
On Tue, 2 Oct 2001, RIDDLE BOX wrote:
> I may have the been trying to do this wrong with that code, but I
> would like the program to look at a file and then when you are done
> looking at that file, I would like it to ask if you would like to look
> at another file, and keep asking that until you quit the program. this
> is my whole code right now. I hope I am on the right track. thanks
> for all your help I am pretty sure that my while statement is wrong
> but I dont know how to get it to work thanks
Here's a small example of doing something until the user types the word
"quit".
###
while 1:
filename = raw_input("What file? ('quit' to quit)")
if filename == 'quit':
break
inp = open(filename)
for line in inp.readlines():
print line
###
What might seem unusual about this code is that it is an infinite loop!
Or, at least, it seems that way. There is one way out of the loop though:
if the user types 'quit' when asked for a filename, we can "break" out of
the loop.
We can write this another way:
###
filename = raw_input("What file? ('quit' to quit)")
while filename != 'quit':
inp = open(filename)
for line in inp.readlines():
print line
filename = raw_input("What file? ('quit' to quit)")
###
In this case, we're rearranging some of the statements, but the effect is
the same --- or, at least, should be the same. I haven't tested this code
out at all yet. *grin*
Try some while loops of your own; if you find that a while loop has gone
out of control, you can press the key combination "Control-c", and that
usually cancels a Python program.
Good luck!