Only allowing a loop of odd numbers in a function
<p>I am teaching myself python but am getting really stuck on this question. It asks to "Write a function which accepts as input a list of odd numbers. Loop over the list of odd numbers and turn each into an even number. Store each even number in a new list and return that new list." </p>

<p>I'm happy with the latter part of the question but struggling with only allowing the input to be odd numbers. </p>

<p>Here's what I've written so far, it works for any odd list you submit e.g. ([1,3,5]) and it works when you start with an even number e.g. ([2,3,5]) but I can't get it to work for when the even number is mid way through the list e.g. ([1,2,3]) - I want it to print this can't be done. </p>

<pre><code>def odd_to_even(x):
for i in x:
    if i %2 == 0:
        print('This is not an odd number')
        break
    else:
        list = []
        for n in x:
            list.append(n -1)
        return list
</code></pre>

<p>I would agree with the comments by @jonrsharpe, @ShadowRanger, and @deceze that you probably don't need to include testing, but it wouldn't hurt.  I'll use @deceze's line for that check here.  Remember, you must declare your list <strong>outside</strong> the loop using it, or the loop will reset it each iteration.  Even better to change the names to make things clearer.</p>

<pre><code>def odd_to_even(input_list):
    if any(i % 2 == 0 for i in input_list): raise ValueError
    output_list = []
    for i in input_list:
        output_list.append(i - 1)
    return output_list
</code></pre>

<p>To incorporate @deceze's good one-liner and keep the validation:</p>

<pre><code>def odd_to_even(input_list):
    if any(i % 2 == 0 for i in input_list): raise ValueError
    return [i - 1 for i in input_list]
</code></pre>

<p>You asked in a comment what is weird about the double looping, so I'd like to add a small explanation for that here.  Sometimes you want to have a loop within a loop, but this was not one of those cases.  You have a single list, and looping over it one time is sufficient in this case for you to:</p>

<ol>
<li>Determine whether all numbers inside the list are odd (validate the list)</li>
<li>Take each number, modify it, and add it to your output list</li>
</ol>

<p>By looping a second time inside your first loop, you would end up looping over the list for each time you looped over the list.  Maybe that phrasing is confusing.  Let's say your input list was <code>[1, 3, 5]</code>.  By using a loop inside a loop, you'd end up creating a new list to output 3 times, because you'd create your output one time for each item in the input.  I hope that helps clear it up for you.</p>

python list function for-loop