Home > database >  Trouble with converting VBA to Python
Trouble with converting VBA to Python

Time:10-12

i have trouble with converting this code in VBA to python function. Always it counts bad control digit.

This is working VBA code :

Public Function kontrolna(liczba As String)
Dim l1, l2, k As Integer
If Len(liczba) Mod 2 = 0 Then
    l1 = 3
    l2 = 1
Else
    l1 = 1
    l2 = 3
End If
k = 0
For x = 1 To Len(liczba)
    If x Mod 2 = 0 Then
        k = k   (Val(Mid(liczba, x, 1)) * l1)
    Else
        k = k   (Val(Mid(liczba, x, 1)) * l2)
    End If
Next x
kontrolna = (10 - (k Mod 10)) Mod 10
End Function

And this is what i do in python but like i say it is wrong. Result for my function always is 2. I try my best but no i have no more ideas how to fix it...

liczba ='900068082' #GOOD CONTROL DIGIT FOR THIS CODE IS 3
def kontrolna(liczba):
l1 = int
l2 = int
if len(liczba) % 2 == 0:
    l1 = 3
    l2 = 1
else:
    l1 = 1
    l2 = 3
k=0

for x in range(len(liczba)):
    if int(x) % 2 == 0:
        k = k   x * l1
    else:
        k = k   x * l2
   
kontrolna = (10 - (k )) % 10

CodePudding user response:

There are 2 minor issues:

  1. Mid(liczba, x, 1) takes the part of String liczba, starting at x, with length 1. In other words: it checks each integer in the String. Hence, your for-loop needs to be changed.

  2. In addition, x needs to incremented, since lists start at 0 in Python, but start at 1 in VBA.

for x in range(len(liczba)):
    val = int(liczba[x])
    if (x 1) % 2 == 0:
        k = k   val * l1
    else:
        k = k   val * l2
  • Related