Remiel Jester Arcay - 11 months ago 42

Python Question

I was just wondering how do I split this into different functions say like maybe 2 or 3 functions? I'm not that good with passing parameters with functions yet. Would you recommend doing that or should I keep it the way it is in one function since it's a while loop? By the way it's for a beginner programming class so that's why its pretty long.

`def sumOfDoublePlace(userChoice):`

lenChecker = len(str(userChoice))

counter = 0

sumNumber = 0

userChoice = int(userChoice)

while counter < lenChecker-1:

counter += 1

endDigit, userChoice = divmod(userChoice, 10)

if counter % 2 == 0:

evenNumber = endDigit * 2

if evenNumber < 10:

sumNumber = sumNumber + evenNumber

else:

oddDigit = endDigit % 10

firstDigit = endDigit // 10

oddSum = oddDigit + firstDigit

sumNumber = sumNumber + oddSum

else:

sumNumber = sumNumber + endDigit

if sumNumber % 10 == 0:

print('This card is valid')

else:

print('This card is invalid')

Answer Source

Overall, I think this should be a single routine. However, you are taking a somewhat tortuous path to the solution. You're doing a *lot* of work to pull digits out of the integer version of the card number, when they're perfectly accessible in the original text.

Here's a start on accessing the string positions you need:

```
def isValidCardNumber(cardNumber):
num_len = len(cardNumber)
last = int(cardNumber[-1]) # grab the last digit; convert to integer
odds = cardNumber[0:-1:2] # positions 0, 2, 4, ... last-1
evens = cardNumber[1:-1:2] # positions 1, 3, 5, ... last-1
# For each list of digits, make a list of their integer equivalents.
# ... and immediately take the sum of those integers.
odd_sum = sum([int(digit) for digit in odds])
even_sum = sum([int(digit) for digit in evens])
```

I leave the rest of this to you. :-)