pythonpython-3.xfunctionreturn-valuedefinition

python function definition to find if all values in a list are even odd or neither


I am struggling in a college beginner's computer science course and just need simple homework help.

Now, we are currently working on function definitions, and I have to write a program that reads a list of integers, and outputs whether the list contains all even numbers, odd numbers, or neither. The input begins with an integer indicating the number of integers in the list. The first integer is not in the list (it just tells the length of the list).

My program must define and call the following two functions. def is_list_even() returns true if all integers in the list are even and false otherwise. def is_list_odd() returns true if all integers in the list are odd and false otherwise. If the list is all even I also have to print 'all even'. If the list is odd, I must print 'all odd'. If the list has both, I must print 'not even or odd'.

I have been able to get all of the integers I need into the list, however the definitions are what I am struggling with (formatting, returning it, etc.). I have pasted the code I have so far below (this website has changed the format of it) but my program produces no output. Any help would be appreciated. Thank you.

n = int(input())

my_list =[]

for i in range(n):

    num = int(input())

    my_list.append(num)

def IsListEven(my_list):

    for i in range(len(my_list)):

        if my_list[i] % 2 == 0:

            return True

        else:

            return False

def IsListOdd(my_list):

    for i in range(len(my_list)):

        if my_list[i] % 2 == 1:

            return True

        else:

            return False

def GetUserValues():

    if IsListOdd(my_list) == True:

        print("all odd")

    elif IsListEven(my_list) == True:

        print("all Even")

    else:

        print("not even or odd")

Solution

  • return will immediately break the loop, so use a holding boolean variable like:

    def IsListEven(my_list):
    
        allEven = True
    
        for i in range(len(my_list)):
    
            if my_list[i] % 2 != 0:
    
                allEven = False
         
        return allEven
    
    def IsListOdd(my_list):
        
        allOdd = True
    
        for i in range(len(my_list)):
    
            if my_list[i] % 2 != 1:
    
                allOdd = False
    
        return allOdd
    
    def GetUserValues():
    
        if IsListOdd(my_list) == True:
    
            print("all odd")
    
        elif IsListEven(my_list) == True:
    
            print("all Even")
    

    But your functions can be one liner if you use all(), an example to check if all is odd

    my_list = [1,3,5]
    print(all(x % 2 == 1 for x in my_list))