0

So I've got a script that needs to read the numbers in a list and the tell me which of those numbers is odd and which ones are even AND if the number is even I need it to be multiplied 1 and then multiplied by 2. I've gotten quite close, but I can't seem to figure out where I'm making my mistake. Any help would be greatly appreciated!

numbers = [1,2,3,4,5]
for n in numbers:
    if n%2 == 0:
        print(n,'is an even number.')
        for n in range(2,5,2):
            product = n
            print('Multiplying by 1 gives',product)
            product = product*2
            print('Multiplying by 2 gives', product)
    else:
        print(n,'is an odd number.')

I'm getting the following output:

1 is an odd number.
2 is an even number.
Multiplying by 1 gives 2
Multiplying by 2 gives 4
Multiplying by 1 gives 4
Multiplying by 2 gives 8
3 is an odd number.
4 is an even number.
Multiplying by 1 gives 2
Multiplying by 2 gives 4
Multiplying by 1 gives 4
Multiplying by 2 gives 8
5 is an odd number.

Whereas my desired output should look like:

1 is an odd number.
2 is an even number.
Multiplying by 1 gives 2
Multiplying by 2 gives 4
3 is an odd number.
4 is an even number.
Multiplying by 1 gives 4
Multiplying by 2 gives 8
5 is an odd number.

3
  • 3
    Simply delete the second for line. It serves no purpose and modifies the original n variable.
    – Selcuk
    Sep 18, 2019 at 0:12
  • What's the point of multiplying a number by 1?
    – Mr. J
    Sep 18, 2019 at 0:18
  • I need it to be multiplied 1 Why? Multiplying a number by 1 has no effect. Sep 18, 2019 at 0:19

2 Answers 2

1

Simply removing for n in range(2,5,2): for loop will give you the desired result, it was overriding the value of n, thus giving you the wrong results.

numbers = [1, 2, 3, 4, 5]
for n in numbers:
    if n % 2 == 0:
        print(n, 'is an even number.')
        product = n
        print('Multiplying by 1 gives', product)
        product = product*2
        print('Multiplying by 2 gives', product)
    else:
        print(n, 'is an odd number.')
0

I think the second for-loop can be omitted. Try this:


for n in numbers:
    if n%2 == 0:
        print(n,'is an even number.\nMultuplying',n,'by 1 
        gives',n,'\nMultiplying',n,'by 2 gives',n*2)

    else:
        print(n,'is an odd number.') 

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.