MC Abstract
MC Abstract

Reputation: 37

How do I pass both the list and the user's number to a function and have it display all numbers in the list that are greater than the user's number?

I need to pass both the list and the user's number to a function and have it display all numbers in the list that are greater than the user's number. This is as far as I've gotten and am stuck. Thanks for any tips.

import random

def randnum():
    random_num = [random.randrange(1,101,1) for _ in range (20)]
    random_num.sort()
    return random_num

def usernum():
    try:
        user_num = int(input("Please enter a number 1 through 100: "))
        if user_num > 100 or user_num < 1:
            print("Please try again.")
            usernum()
    except ValueError:
        user_num = print("Error. Please try to use integers while entering a number 1-100")
        usernum()
    return user_num

def main():

Upvotes: 2

Views: 52

Answers (1)

Lo&#239;c
Lo&#239;c

Reputation: 11942

I think you are missing some code, but your function could be something like that :

def getHigherNumbers(userNumber, listNumbers):
    return [x for x in listNumbers if x > userNumber]

Also there is a bug in your usernum():

When there is an error you should use return usernum() instead of just usernum() since there'll be recursion.

To answer your question in the comments, here is how your code could look :

import random

def randnum():
    random_num = [random.randrange(1,101,1) for _ in range (20)]
    random_num.sort()
    return random_num

def usernum():
    try:
        user_num = int(input("Please enter a number 1 through 100: "))
        if user_num > 100 or user_num < 1:
            print("Please try again.")
            return usernum()
    except ValueError:
        print("Error. Please try to use integers while entering a number 1-100")
        return usernum()
    return user_num

def getHigherNumbers(user_num, random_num):
    return [x for x in random_num if x > user_num]

def main():
    random_num = randnum()
    print('random nums : %s' % random_num)
    user_num = usernum()
    print('user num : %s' % user_num)
    greater_nums = getHigherNumbers(user_num, random_num)
    print('greeter numbers : %s' % greater_nums)

if __name__ == '__main__':
    main()


# random nums : [1, 4, 11, 14, 18, 24, 27, 29, 31, 37, 37, 41, 45, 59, 59, 66, 83, 87, 90, 99]
# Please enter a number 1 through 100: 12
# user num : 12
# greeter numbers : [14, 18, 24, 27, 29, 31, 37, 37, 41, 45, 59, 59, 66, 83, 87, 90, 99]

Upvotes: 2

Related Questions