Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialthanh trung
4,246 Pointshaving problem making function that return odd number
having problem making function that return odd number. if anyone tells me, what have i done wrong here
def odds(number):
for num in number:
oddsNum = number[odd(num)]
return oddsNum
3 Answers
Tree Casiano
16,436 PointsHere's how I would approach the problem.
number_list=[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
def odds(number):
odd_list = []
for num in number:
if num % 2 == 1:
odd_list.append(num)
print(odd_list)
odds(number_list)
In the function, I created a blank list to which I appended only the numbers that were not evenly divisible by 2. I used the modulus operator.
EDIT: I just saw Kenneth's comment that the challenge is asking for the numbers that have an odd index. I think this will do it:
def odds(number_list):
return number_list[1::2]
Kenneth Love
Treehouse Guest TeacherThe CC isn't asking for numbers that are odd, but for numbers that have an odd index.
thanh trung
4,246 Pointsi tried this and it works for me
''' def odd(number):
return number[1::2]
'''
however, i dont know how to do the next exercise. Where do i begin?
Kenneth Love
Treehouse Guest TeacherYou make a function that sends back the first 4, and last 4, items in an iterable. The 4th-from-last item in an iterable can be gotten with [-4]
.
thanh trung
4,246 Pointsi know that but i dont know how to put that in the expression. Can i make it like this?
''' def first_and_last_4(number): return number [::4:-4] '''
Kenneth Love
Treehouse Guest TeacherNope, but you can always add two slices together and return that.