1

This is a check digit exercise.

A=str(56784321)
for x in [0,2,4,6]:
    B = int(A[x])*2
        if len(str(B))==2:
            B = int(str(B)[0])+int(str(B)[1])
            print (B)

Output:

1
5
8
4

How can I use further code to add 4 of them together?

Josh Crozier
  • 233,099
  • 56
  • 391
  • 304
PyJar
  • 83
  • 2
  • 3
  • 13

1 Answers1

1

With minimal changes to your code, you can use Python generators. See this question for a good reference.

def split_str(A):
  for x in [0,2,4,6]:
    B=int(A[x])*2
    if len(str(B))==2:
      B= int(str(B)[0])+int(str(B)[1])
    yield B

A=str(56784321)
for f in split_str(A):
  print f
print 'Sum is', sum(split_str(A))

Prints:

1
5
8
4
Sum is 18
Community
  • 1
  • 1
Vladimir Sinenko
  • 4,629
  • 1
  • 27
  • 39
  • How can you do it with out putting them into function? – PyJar Oct 26 '12 at 02:48
  • @pythonBeginner, you could create an empty list before your code and append B values to it instead of yielding them. This is not that hard, you could try that yourself as an exercise. – Vladimir Sinenko Oct 26 '12 at 02:54
  • @VladimirSinenko Thanks for your advise, but could you give me an example of creating an empty list? – PyJar Oct 26 '12 at 03:03
  • It's created like this: `var = []`. You'll further need `var.append()` operator to populate the list. I suggest you to read the Python tutorial from the start. – Vladimir Sinenko Oct 26 '12 at 03:07