I'm creating a program that checks if credit card numbers are valid.
I'll post a picture of exactly what the instructions are so you have a better understanding of what I'm going for here. The instructions show that he's asked us to create two functions to calculate the sum for the odd numbers. so far I have this:
def main():
cardNum=int(input("Enter credit card number as a long integer: "))
singleDigit=getDigit(cardNum)
evenNum=sumOfDoubleEvenPlace(cardNum,singleDigit)
oddNum=sumOfOddPlace(cardNum)
print(evenNum)
print(oddNum)
checker=isValid(cardNum,sumOfDoubleEvenPlace,sumOfOddPlace)
if checker==True:
print(cardNum,"is valid")
else:
print(cardNum,"is invalid")
def isValid(cardNum:int,sumOfDoubleEvenPlace:int,sumOfOddPlace:int):
checker=False
singleDigit=getDigit(cardNum)
evenNum=sumOfDoubleEvenPlace(cardNum,singleDigit)
oddNum=sumOfOddPlace(cardNum)
if (oddNum+evenNum)%10==0:
checker=True
else:
checker=False
return checker
def getDigit(cardNum:int)->int:
for ch in str(cardNum)[0::2]:
if 2*int(ch)<10:
singleDigit=2*int(ch)
else:
singleDigit=((2*int(ch))%10)+((2*int(ch))//10)
return singleDigit
def sumOfDoubleEvenPlace (cardNum:int,singleDigit:int)->int:
evenNum=0
i=0
while i<(len(str(cardNum))//2):
evenNum+=singleDigit
i+=1
return evenNum
def sumOfOddPlace(cardNum:int)->int:
oddNum=0
for ch in str(cardNum)[1::2]:
oddNum+=int(ch)
return oddNum
if __name__=="__main__":
main()
I'm stuck on the functions getDigit() and sumOfDoubleEvenPlace(). I don't know how to convert the doubled number into a single digit in getDigit() and send them to sumOfDoubleEvenPlace() one at a time to be summed.
I understand that this can easily be completed in one function but that's not what my teacher wants :/
:::::UPDATE::::: I got a better understanding of what the two functions do from my teacher. I updated my code but now I'm running into global/local variable issues as the two functions reference each other.
I changed getDigit() and sumOfDoubleEvenPlace() to the following:
def getDigit(cardNum:int)->int:
doubleDigit=sumOfDoubleEvenPlace (cardNum)
if doubleDigit<10:
singleDigit=doubleDigit
else:
singleDigit=(doubleDigit%10)+(doubleDigit//10)
def sumOfDoubleEvenPlace (cardNum:int)->int:
evenNum=0
doubleDigit=0
singleDigit=getDigit(doubleDigit)
for ch in str(cardNum)[0::2]:
doubleDigit=2*int(ch)
getDigit(doubleDigit)
evenNum+=singleDigit
return evenNum
getDigit()has areturninside a for loop. That loop will only loop once.