Python Forum
won't exit a loop, please help
Thread Rating:
  • 1 Vote(s) - 5 Average
  • 1
  • 2
  • 3
  • 4
  • 5
won't exit a loop, please help
#1
can't upload program code
Reply
#2
Hi, I'm new to python, about a couple of months learning on my own,
I see that people are very helpful on this forum, I have a dilemna on this program I'm writing.
If I enter a name on the first entry, then I enter "n" for the rest of the entries, I get an error saying
print ("here is the list of names having the letter/s (",(letters),") in them")
NameError: name 'letters' is not defined,


Now I understand that to mean that since I skipped past entering any letters for the search option
entry, that the variable (letters) is not defined.

HOWEVER, the dilemna is this, I wrote this set of instructions to get me out of the loops,
while redo==0:
srch=0
while srch==0:
user=input("would you like to do a search of the list? (Y/N) ")
if user=="n":
srch=1
redo=1
--------------------------------------------------------------------------
The instruction "REDO=1" should take the program out of the "redo" [while loop], but instead it
drops down to the instruction on line 74 to print out "letters" which never was entered.


If you run this program, it works quite well, except when entering "n" for all the (Y/N)
options.

Can anyone figure out why the program will not leave the [while loop} containing "REDO"

This is a mystery to me.

Thankyou for your time and help.



Here is the program.

import os
class klass:
     '"docstring'"
    def_init_(self):
        self.attribute="var"
        if len(self.attribute) <2:
            pass

print("")
listgather=[]
lista=[]
lista_reload=[]
flg=0
while flg==0:
    user=input("enter a name>> ")
    lista.append(user)
    lista_reload.append(user)
    new=0
    while new==0:
        user=input("would you like to make another entry (Y/N) ")
        if user=="n":
            flg=1
            new=1
            for item in (lista):
                listfile="word.txt" 
                file=open(listfile,"a")
                file.write(item)
                file.write("\n")
            file.close()
        elif user=="y":
            new=1
            print("")
        else:
            print("enter (Y or N)")
print("")
v=0
while v==0:
    user=input("would you like to view the list? (Y/N)" )
    if user=="y":
        print ("here is the list to view  ,",(lista))
        v=1
    elif user=="n":
        v=1
    else:
        print ("enter (Y or N)")
print ("done")
redo=0
while redo==0:
    srch=0
    while srch==0:
        user=input("would you like to do a search of the list? (Y/N) ")
        if user=="n":
            srch=1
            redo=1
        elif user=="y":
             letters=input("Enter a letter/s to use in your search >>  ")
             inhere=0
             for item in (lista):
                    if letters in (item):
                        ndx=lista.index(item)
                        found=lista[ndx]
                        print("")
                        print ("YES ",(letters)," is in here")
                        print("")
                        print ((found)," is in the list")
                        lista[ndx]=""
                        listgather.append(found)
                        inhere=1
                        srch=1
             if inhere==0:
                 print("")
                 print((letters)," NOT in here")
             elif inhere==1:
                 print("")
                 print ("We have found, ",(found)," in the list")
                
        else:
            print ("Enter (Y or N)")
    
    print ("test")    
    print("")
    print ("here is the list of names having the letter/s  (",(letters),")  in them")
    print ("")
    print (listgather)
    print("")
    askredo=input("would you like to continue (Y/N)>> ")
    if askredo=="n":
        redo=1
    elif askredo=="y":
        lista=[]
        listgather=[]
        for items in lista_reload:
            lista.append(items)
            srch=0
    else:
        print ("enter (Y or N)")
print ("done")
Reply
#3
Hi, I'm new to python, about a couple of months learning on my own,
I see that people are very helpful on this forum, I have a dilemna on this program I'm writing.
It would seem that the print ("test") statement should not print, when user enters "N" because the flag redo is set to "1"
yet it still runs that line of code.







Here is the program.

import os
class klass:
     '"docstring'"
    def_init_(self):
        self.attribute="var"
        if len(self.attribute) <2:
            pass


#my program snippet starts here
redo=0
while redo==0:
    srch=0
    while srch==0:
        user=input("would you like to do a search of the list? (Y/N) ")
        if user=="n":
            srch=1
            redo=1
    print ("test")
print ("done")
Reply
#4
Quote:can't upload program code
use cut and paste, and put code in code tags, see BBCODE
Reply
#5
You don't have any condition on the print test statement, so it should print every time
If you want it to print only when redo is equal to zero, do:
if redo == 0:
    print ("test")
Reply
#6
Thank you, I appreciate your reply, I only put the “test” statement in there to show how the
Redo while loop is not exiting when the user inputs a “N”.

Here is a better snippet of code to explain what I’m asking about.







Here is the program.
import os
class klass:
     '"docstring'"
    def_init_(self):
        self.attribute="var"
        if len(self.attribute) <2:
            pass

#my code starts here
redo=0
while redo==0:
    srch=0
    while srch==0:
        user=input("would you like to do a search of the list? (Y/N) ")
        if user=="n":
            srch=1
            redo=1
            print("")
            print ("redo is set to a one")
            print("")
    print ("WHY is this line showing up I set the “redo” flag to a one”")
    print ("this line of code is still under the “while” loop condition “REDO”")
    print("")
    print("")
print ("This line of code I thought should be the ONLY line showing up")
print ("This line of code is OUTSIDE of the “while” loop of “REDO”")
print("")
print ("Thank you again for your time and help much appreciated")
Reply
#7
Don't forget that user may enter Y, y, N, n or garbage, can check
if user.lower() == 'n':
the following prints because it's at same indent level as second while, which means:
loop in second while until srch != 0, then continue on line 21
    print ("WHY is this line showing up I set the “redo” flag to a one”")
    print ("this line of code is still under the “while” loop condition “REDO”")
    print("")
    print("")
Reply
#8
Are you inputting a "N" or a "n"? Your code is only set up to acknowledge a "n".
Reply
#9
The statement at line 20 is part of the block that executes with the while conditional starting at line 20.

Let's say you enter "n" while prompted. Yes, the redo variable is now set to 1, but the first while loop is still executing the rest of the statements within (lines 12-24). The conditional at line 11 isn't reevaluated until the block finishes.

Any time you get stuck like this, it's sometimes interesting and instructive to attempt to run the program in a debugger. I wrote a short "how to" on using the Python debugger, I hope it helps.

While you are learning about a language, a debugger is helpful because you can execute the program one line at a time. Sometimes the state of the program surprises you and you get to see all the assumptions you made go up in a puff of smoke.
Reply
#10
Thank you everyone who contributed to my question.
I followed your advice, and my program is working properly now.
As a token of my appreciation, Using what I have learned so far,
I wrote a program to give each person
A personal reply and a ‘thank you”!

Here is the program.
import os
class klass:
     '"docstring'"
    def_init_(self):
        self.attribute="var"
        if len(self.attribute) <2:
            pass

#("My code starts here")


print("")
print ("Hello everyone, This is a token of appreciation of how you helped me")
print("I would like to make an interactive thank you to every one of you individually")
print("")
listhelper=["Larz60+","stullis","jdjeffers"]
listanswer=["You don't have any condition on the print test statement, so it should print every time",
       "Are you inputting a 'N' or a 'n'? Your code is only set up to acknowledge a 'n'",
       "The statement at line 20 is part of the block that executes with the while conditional starting at line 20."
       "Let's say you enter 'n' while prompted. Yes, the redo variable is now set to 1, but the first while loop is"
       "still executing the rest of the statements within (lines 12-24). The conditional at line 11 isn't reevaluated until the block finishes."]
listthankyou=["Larz60+, please forgive me, I didn't quite undrstand at first what you were saying"
        "but now I do, your right, I needed a 'IF' statement to preceed the next line."
        "I added it to my main program and it works perfectly without errors now."
        "                 THANK YOU                 ","stullis Hi, yes I was entering a lowercase 'n', anything else would keep looping back to the input"
        "                 THANK YOU                ","jdjeffers, that explanation really gave me a sense of understanding how indentation works"
        "I was always under the assumption, that only indented lines of code was inside the loop, but your explanation made me realize that"
        "any lines of code directly under the loop statements are executed as well, I did some test statements with indentation and non indentation"
        "and found that nonindentation does get worked on as well as long as it is under a 'while' statement."
        "               THANK YOU                    "]


reply=0
while reply==0:
    user=input("Would you like to have a personal thankyou? (Y/N) ")
    if user=="y":
        print ("yes")
        print("")
        verify=input("please enter your forum 'NAME'>> ")
        if verify in (listhelper):
            ndx=listhelper.index(verify)
            reply=listanswer[ndx]
            print("")
            print ((verify)," replied, ",(reply))
            print("")
            thankyou=listthankyou[ndx]
            print (thankyou)
            redo=1
            reply=1
        else:
            print("whoops")
            print("")
            print("Please enter your 'name' exactly as on your forum tag")
    elif user=="n":
        print("no")
        reply=1
    else:
        print ("please enter (Y or N)")
print("")
print ("done")
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  python difference between sys.exit and exit() mg24 1 1,764 Nov-12-2022, 01:37 PM
Last Post: deanhystad
  While loop doesn't exit KenHorse 3 1,967 Jun-20-2021, 11:05 PM
Last Post: deanhystad
  Exit Function - loop Tetsuo30 2 2,025 Sep-17-2020, 09:58 AM
Last Post: Tetsuo30
  Struggling to exit this while loop fatherted99 5 2,413 Feb-08-2020, 07:46 PM
Last Post: fatherted99
  Using break to exit a loop help JJG 4 4,145 Dec-09-2017, 03:02 AM
Last Post: JJG
  How to exit infinite While Loop? Fran_3 3 4,052 Aug-10-2017, 05:29 PM
Last Post: wavic

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020