Skip to content
Advertisement

Python: Random list with odds and even numbers

New to python. I’ve got an assignment where I have to generate a random list of numbers between -10 and 30 and then proceed to call odds and evens from the list. So far I’ve got this, but I have no idea how to proceed and how to make it actually work properly. Also I need to figure out how to also check positive and negative numbers from the list, but currently I’m just stuck at odds and evens.

def Osio7(): ### function to generate 40 random numbers between -10 and 30
randomlist = random.sample(range(-10, 30), 40)
print (randomlist)

def odd_evens(): ## odds_evens function
    odds = []   
    evens = []
    for value in randomlist:
        if value % 2 == 0:
            evens.append(value)
        else:
            odds.append(value)
        print ("Even numbers: ", evens) 
        print ("Odd numbers: ", odds)
        odd_evens()
          
def positive_negatives(): ### postive_negatives function
    positives = []
    negatives = []
    for value in randomlist:
        if value >= 0:
            positives += 1
            positives.append(value)
        else:
            negatives += 1
            negatives.append(value)
        print ("Positive numbers in the list: " + positives) 
        print ("Negative numbers in the list: " + negatives) 
        positive_negatives()

Advertisement

Answer

You’re maybe looking for something like this:

import random


def Osio7():
    randomlist = random.sample(range(-10, 30), 40)
    odds = []  # Create empty lists for the odds...
    evens = []  # ... and evens
    for value in randomlist:  # Iterate over the random list
        if value % 2 == 0:  # It's even?
            evens.append(value)  # Add to the even list.
        else:  # Otherwise it's odd, so...
            odds.append(value)  # Add to the odd list.
    # (do something with `odds` and `evens`)
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement