0

I am trying to convert my credit solution from C to python, but for some reason it is not working. Attached is my code and the problems

from cs50 import get_int

card, a, m, v = False, False, False, False
sum = 0
num = get_int("Number: ")
numcopy = num
i = 0
for j in range(num):
    if (i % 2) == 0:
        digit = num % 10
        sum += digit
    else:
        digit = num % 10
        digit *= 2
        while digit > 1:
            digitmultiply = intdigit % 10
            sum += digitmultiply
            digit /= 10
    num /= 10
    i += 1
if (sum % 10) == 0:
    card = True
while numcopy > 100:
    numcopy /= 10
if numcopy in [34, 37]:
    a = True
if numcopy in [51, 52, 53, 54, 55]:
    m = True
if (numcopy / 10) == 4:
    if i == 13 or i == 16:
        v = True
if card and v:
    print("VISA")
elif card and m and i == 16:
    print("MASTERCARD")
elif card and a and i == 15:
    print("AMEX")
else:
    print("INVALID")

My code keeps getting stuck in the for loop. I have tried making print lines under the first if (i % 2) == 0: loop, and it keeps looping and giving me the same value, a float (Depending on the input) like 67.97306575341835 and my digit value is consistently 0 while the program is still stuck in the loop.

I am unable to figure out what is wrong with my program, and would greatly appreciate any input or advise. Thank you everyone!

1 Answer 1

1

Unlike C, / will perform true floating point division in Python. To get integer division (and discard the remainder), use // instead.

Regarding being stuck in the for loop, range(num) will loop all the way up to the actual value of num (over four quadrillion iterations for a typical VISA!). Perhaps try something like:

while num > 0:

One small note: sum is the name of a standard function in python. While you can name your variable this and it will take precedence, it's better practice to choose something else.

1
  • Thank you sir! That really helped. And yes i will take note in the future, cheers!
    – Bob Tan
    Commented Dec 10, 2020 at 5:43

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .