HarryVu176
HarryVu176

Reputation: 41

How can I retain zero in python for calculation?

So I supposed to verify if the input number is a UPC number or not. I have to allowed leading zeros and accounted it in the calculation.

Here is my current code, it works for all number except number has leading zeros:

Condition for UPC code valid:

def UPC_code(num):
    sum_digit = 0
    index = 0
    num_temp = str(num)[:-1]
    len_nt = len(num_temp)

    for digit in num_temp:                  
        if (index + 1) % 2 != 0:            # If number position is odd
            sum_digit += int(digit) * 3     # Sum = digit * 3
            if index < len_nt:              # Increase index till end
                index += 1
        elif (index + 1) % 2 == 0:          # If number position is even
            sum_digit += int(digit) * 1     # Sum = digit * 1
            if index < len_nt:
                index += 1
    # print(sum_digit)

    res_digit = sum_digit % 10
    if 1 <= res_digit <= 9:
        res_digit = 10 - res_digit      # Res digit meet condition = 10 - res digit

    if res_digit == num % 10:
        return True
    elif res_digit != num % 10:
        return False
    else:
        print("Something went wrong")
# End UPC_code()

Call UPC_code()

import code_check.py as cc

num = str(input())
num_int = int(num)
if cc.UPC_code(num_int) is True and num_int != 0:
    print(num, "valid UPC code.")
else:
    print("Not valid")

Expected input:

042100005264

Expected output:

042100005264 valid UPC code

Actual output:

Not valid

Upvotes: 0

Views: 504

Answers (1)

2e0byo
2e0byo

Reputation: 5954

it works for all number except number has leading zeros

As you have doubtless discovered, python does not allow you to write 0700. Historically that would have meant 0o700, or 448, which is likely not what you want anyhow...

In this case the solution is simple. If you need to handle numbers like 00007878979345, handle strings.

Thus refactor your code to take a string. As a bonus, int("000008") is 8, so when you need the number as a number you don't even have to do anything.

Upvotes: 2

Related Questions