I donä't get while-loops

Discussion in 'Python' started by ssecorp, Aug 2, 2008.

  1. ssecorp

    ssecorp Guest

    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!"
     
    ssecorp, Aug 2, 2008
    #1
    1. Advertisements


  2. 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
     
    Stefaan Himpe, Aug 2, 2008
    #2
    1. Advertisements

  3. ssecorp

    ssecorp Guest

    oops, embarrassing, I created the while loop not to use recursion then
    I still did...
     
    ssecorp, Aug 2, 2008
    #3
  4. 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!"
     
    Tyler Breisacher, Aug 3, 2008
    #4
    1. Advertisements

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 (here). After that, you can post your question and our members will help you out.