Joey - 1 year ago 114

Python Question

Hey guys I'm fairly new to the programming world. For a school practice question I was given the following text and I'm suppose to convert this into code. I've spent hours on it and still can't seem to figure it out but I'm determine to learn this. I'm currently getting the error

`line 7, in <module> if i % 2 == 0: TypeError: not all arguments converted during string formatting`

What does this mean? I'm still learning loops and I'm not sure if it's in the correct format or not. Thanks for your time.

`# GET user's credit card number`

# SET total to 0

# LOOP backwards from the last digit to the first one at a time

# IF the position of the current digit is even THEN

# DOUBLE the value of the current digit

# IF the doubled value is more than 9 THEN

# SUM the digits of the doubled value

# ENDIF

# SUM the calculated value and the total

# ELSE

# SUM the current digit and the total

# ENDIF

# END loop

# IF total % 10 == 0 THEN

# SHOW Number is valid

# ELSE

# SHOW number is invalid

# ENDIF

creditCard = input("What is your creditcard?")

total = 0

for i in creditCard[-1]:

if i % 2 == 0:

i = i * 2

if i > 9:

i += i

total = total + i

else:

total = total + i

if total % 10 == 0:

print("Valid")

else:

print("Invalid")

Recommended for you: Get network issues from **WhatsUp Gold**. **Not end users.**

Answer Source

well, i can see 2 problems:

1)when you do:

```
for i in creditCard[-1]
```

you dont iterate on the creditCard you simply take the last digit. you probably meant to do

```
for i in creditCard[::-1]
```

this will iterate the digits from the last one to the first one

2) the pseudocode said to double the number if its POSITION is even, not if the digit itself is even

so you can do this:

```
digit_count = len(creditCard)
for i in range(digit_count -1, -1, -1):
digit = creditCard[i]
```

or have a look at the `enumerate`

built-in function

edit:

complete sample:

```
creditCard = input("What is your creditcard?")
total = 0
digit_count = len(creditCard)
for i in range(0, digit_count, -1):
digit = creditCard[i]
if i % 2 == 0:
digit = digit * 2
if digit > 9:
digit = digit / 10 + digit % 10 # also noticed you didnt sum the digits of the number
total = total + digit
if total % 10 == 0:
print("Valid")
else:
print("Invalid")
```

Recommended from our users: **Dynamic Network Monitoring from WhatsUp Gold from IPSwitch**. ** Free Download**