sai
sai

Reputation: 91

while loop not terminating python

i am writing an interactive program that displays y/n after selecting the option. if at begining itself i press s or c the while loop terminates. if i select some no first time "say 5" the 5th option turns to y but after that if i press "s" or "c" it shows the 5th entry as "n" and the program is not exited. not sure what's going wrong. beginner question.(alternate solution is also appretiated, can't import other packages as well)

import os,time
selected_list=[]
def px_filter_menu(num):
    os.system("clear")
    data = ["p1","p2","p3","p4","p5","p6","p7","p8","p9","p10","p11","p12","p13","p14","p15","p16","p17","p18","p19","p20","p21","p22","p23","p24","p25","p26"]

    print("============================================================================\n= Filter selection menu")
    print("============================================================================\n\n")

    gap =5

    for count , item in enumerate(data, 1):
        if count <10:
            if data[count-1] in selected_list:
                print("{0}.  {1} {2}".format(count,item.ljust(gap),"[y]"))
            else:
                print("{0}.  {1} {2}".format(count,item.ljust(gap),"[n]"))
        else:
            if data[count-1] in selected_list:
                print("{0}. {1} {2}".format(count,item.ljust(gap),"[y]"))
            else:
                print("{0}. {1} {2}".format(count,item.ljust(gap),"[n]"))

    print("\n\n[S] save and exit")
    print("\n\n[C] if you press C and wish to make changes please remove the PX and add again\n")

    input = raw_input("enter the desired number ")
    
    if len(input.strip()) ==0:
        print("first")
        time.sleep(2)
        px_filter_menu(-1)
       
    while True:
        if input.upper()=="S":
            print("5")
            time.sleep(2)
            break

        elif input.upper()=="C":
            del selected_list[:]
            #by default all protocol goes
            print("6")
            time.sleep(2)
            break

        elif input.isdigit() and data[int(input)-1] in selected_list:
            print(input)
            selected_list.remove(data[int(input)-1])
            print("3")
            time.sleep(2)
            px_filter_menu(-1)

        elif input.isdigit():
            selected_list.append(data[int(input)-1])
            print("4")
            time.sleep(2)
            px_filter_menu(-1)
        else:
            px_filter_menu(-1)
    return

px_filter_menu(-1)

Upvotes: 0

Views: 72

Answers (1)

Robby the Belgian
Robby the Belgian

Reputation: 663

The problem is that for the cases where a number is given as input, you recursively call the same function again. If / when that call exits, execution continues in this call, going back into the while loop.

Since you have a while loop, you do not need recursive calls. The loop will take care of things being repeated, if necessary.

Upvotes: 3

Related Questions