I donä't get while-loops

S

ssecorp

in read2 it never quits when I write quit, why?

def read():
expr = raw_input("Lisp> ")
if expr != "quit":
print parse(expr)
read()
else:
print "Good session!"

def read2():
expr = ""
while expr != "quit":
expr = raw_input("Lisp> ")
print parse(expr)
read2()
print "Good session!"
 
S

Stefaan Himpe

def read2():
expr = ""
while expr != "quit":
expr = raw_input("Lisp> ")
print parse(expr)
read2() ^^^^^^^^^^^^^^^^^
print "Good session!"


You shouldn't call read2() inside read2()...
just remove that line and retry...

Each time you call read2() recursively, a
new expr is initialized to "", so the condition
never becomes true
 
S

ssecorp

oops, embarrassing, I created the while loop not to use recursion then
I still did...
 
T

Tyler Breisacher

You're actually calling the read2() function from within read2(). This
is called recursion, and it is *not* what you want in this case, since
it unnecessarily fills up your call stack. Remember that a while loop
automatically goes back to the top without you having to re-call your
function. I would just do this:

def read3():
expr = raw_input("Lisp> ")
while expr != "quit":
print parse(expr)
expr = raw_input("Lisp> ")
print "Good session!"
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,537
Members
45,022
Latest member
MaybelleMa

Latest Threads

Top