[英]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():
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()
:您的usernum()
还有一个错误:
When there is an error you should use return usernum()
instead of just usernum()
since there'll be recursion.当出现错误时,您应该使用return usernum()
而不是usernum()
因为会有递归。
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]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.