Day 12
I am trying to do this quiz question:
βThe odd_numbers function returns a list of odd numbers between 1 and n, inclusively. Fill in the blanks in the function, using list comprehension. Hint: remember that list and range counters start at 0 and end at the limit minus 1".β
And I have to correct this code:
def odd_numbers(n):
return [x for x in ___ if ___]
So it returns this output:
print(odd_numbers(5)) # Should print [1, 3, 5]
print(odd_numbers(10)) # Should print [1, 3, 5, 7, 9]
print(odd_numbers(11)) # Should print [1, 3, 5, 7, 9, 11]
print(odd_numbers(1)) # Should print [1]
print(odd_numbers(-1)) # Should print []
So I tried this:
def odd_numbers(n):
return [x for x in range (1,11) if x % 2 != 0]
And I got some right and some wrong. The smart quiz offered this:
Here is your output:
[1, 3, 5, 7, 9]
[1, 3, 5, 7, 9]
[1, 3, 5, 7, 9]
[1, 3, 5, 7, 9]
[1, 3, 5, 7, 9]
Not quite, odd_numbers(5) returned [1, 3, 5, 7, 9] instead
of [1, 3, 5]. Remember that list comprehensions let us use a
conditional clause. What's the condition to determine
whether a number is odd or even?
Now I will try and figure out how to write it correctly.