Reputation: 9
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."
I'm happy with the latter part of the question but struggling with only allowing the input to be odd numbers.
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.
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
Upvotes: 1
Views: 5033
Reputation: 6596
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 outside the loop using it, or the loop will reset it each iteration. Even better to change the names to make things clearer.
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
To incorporate @deceze's good one-liner and keep the validation:
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]
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:
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 [1, 3, 5]
. 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.
Upvotes: 3