Home > Software design >  How can I use a for loop to sort even numbers from odd numbers?
How can I use a for loop to sort even numbers from odd numbers?

Time:01-13

I'm trying to take a list of numbers and sort them by whether they are even or odd with a for loop. I can't seem to make it work. I've gotten it to run and give me back ALL the numbers but that's not what I'm looking for. Please help me with this code so that I can actually make it tell me whether a number is even or odd and then omit it if it's even.

def is_odd(num):
    if(num % 2) == 0:
        return(True)
            
    else: return(False)
some_numbers = [91, 88, 38, 103, 199372, 3, 4945, 20098]
for num in list(some_numbers):
    if num == is_odd:
        continue
        print(num)

I know I need something after this but currently when I run the code nothing happens which is concerning.

CodePudding user response:

You are trying to check if num is equal to the function is_odd, which will always return False as they are not equal.

Here is a modified version of your code that should work:

def is_odd(num):
    if(num % 2) == 0:
        return False
    else:
        return True

some_numbers = [91, 88, 38, 103, 199372, 3, 4945, 20098]
for num in some_numbers:
    if not is_odd(num):
        continue
    print(num)

CodePudding user response:

Hope this helps!

some_numbers = [91, 88, 38, 103, 199372, 3, 4945, 20098]
for num in list(some_numbers):
    if num % 2 != 0:
        print(num)

or if you'd like to implement your function:

def is_odd(num):
    if num % 2 == 0:
        return False 
    else: 
        return True
        
some_numbers = [91, 88, 38, 103, 199372, 3, 4945, 20098]
for num in list(some_numbers):
    if is_odd(num):
        print(num)
  • Related