Home > Mobile >  I wrote a code that would print the odd numbers or the even numbers in a list according to users cho
I wrote a code that would print the odd numbers or the even numbers in a list according to users cho

Time:10-15

I created a code that takes a list from the user and then asks the user to choose from printing only the odd numbers or the even numbers. But whenever the user choice is taken, the execution freezes. Using keyboard interrupt, I find that the execution stopped in either the odd or even function. Please help !!!

here is the code:

    from os import lstat

    def odd(lst,oddlst):
        for i in range(0,n):
            while(lst[i]%2!=0):
                oddlst.append(lst[i])
        return oddlst

    def even(lst,evenlst):
        for i in range (0,n):
            while(lst[i]%2==0):
                evenlst.append(lst[i])
        return evenlst

    lst = []
    oddlst = []
    evenlst = []
    n = int(input("enter number of elements \n"))
    print("\nenter the elements \n")
    for i in range(0,n):
        num = int(input())
        lst.append(num)
    print(lst)

    choice = input(" Do you want to print odd elements or even elements \n (odd/even) 
    \n")
    if(choice=="odd"):
        odd(lst,oddlst)
        print(oddlst)
    elif(choice=="even"):
        even(lst,evenlst)
        print(evenlst)
    else:
        print("invalid choice")

CodePudding user response:

Perhaps you meant to use an if instead of a while in your odd and even functions.

The reason your execution "freezes", is that you run into an infinite loop. In either while, the i-th element gets checked, then appended to a list. But the condition, against which you are checking, doesn't change, neither does the index i.

Changing your whiles to ifs should solve your problem.

Also, for a more elegant solution to your problem, have a look at:
https://docs.python.org/3/library/functions.html#filter
How to filter a list

  • Related