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?

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

4 Comments

How can you do it with out putting them into function?
@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.
@VladimirSinenko Thanks for your advise, but could you give me an example of creating an empty list?
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.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.