0
numbers = raw_input("Enter numbers: ")
numbers = [numbers]
numbers = list(numbers[0])
numbers = [int(x) for x in numbers]
numbers[::2] = [2*x for x in numbers[::2]]
for x in numbers: #code stops working as i want here
    if x == 10:
        x = 1
    elif x == 12:
        x = 3
    elif x == 14:
        x = 5
    elif x == 16:
        x = 7
    elif x == 18:
        x = 9
print(numbers)

Basically I want it to take the numbers I give it, put it into a list, split that list, change all elements in the list to integers, and for every other element in the list, double it, and (here's where it stops working) take the possible 2 digit numbers from doubling 5, 6, 7, 8, or 9 and add the digits.

I think the for, if, and elif statements are right but I think their bodies are wrong. What do I do to change x if it's not like a variable? (x = 1)

Or am I doing the last step all wrong? Thanks.

Jacob Wheeler
  • 53
  • 1
  • 8

3 Answers3

1

The assignment x = 1 is simply rebinding the name x to the value 1. This does not modify the contents of numbers.

If you want to change a value contained in a list you must explicitly do so by using:

numbers[index] = value

For example:

for i, x in enumerate(numbers):
    if x >= 10: # not actually required: 0<= x < 10 implies x%10 == x and x//10 == 0
        numbers[i] = x%10 + x//10

Note that if you have a two digit number then x % 10 is equal to the first digit while x // 10 (integer division/quotient) is equal to the second digit.

In fact you could even do:

numbers[i] = sum(divmod(x, 10))
Bakuriu
  • 98,325
  • 22
  • 197
  • 231
0

You can not change the variable indicating an item in a collection due to loop scope. Try this instead:

for i, x in enumerate(numbers): 
    numbers[i] = sum(map(int, str(x)))
Malik Brahimi
  • 16,341
  • 7
  • 39
  • 70
0
def f(x):
    if x in (10, 12, 14, 16, 18):
        return x-9
    else return x

Instead of the loop at the end,

numbers = [f(n) for n in numbers]

Of course, you can put the definition of f in the list comprehension, but it starts looking a bit cramped.

saulspatz
  • 5,011
  • 5
  • 36
  • 47