Please note that i am a VERY confused BEGINNER but i'm enjoying the course and eager to learn. Below is my code and i'd like to understand a few things:
Why if i define main i get multiple errors such as: "name 'card' is not defined", whereas if i don't define main everything runs smoothly?
I copied the split_to_digits function and to my knowledge i assumed it returned a list, so i'm trying to loop through the list "everyotherdig" to sum the digits but if i try and print the sum it says "built in function sum"
Any other error i surely committed if you'd be so kind as to explain it to me i would be very grateful.
# get user input
while True:
try:
card = int(input("Credit card number:"))''
if card > 0:''
break
except ValueError:
print("INVALID")
#Convert card back into a string
card = str(card)
if len(card) not in (13,15,16):
print("INVALID")
#Store valid prefixes into a tuple
prefixes = ["4","34","37","50","51","52","53","54","55"]
#Check if user input is valid
x = card.startswith(tuple(prefixes))
if x == False:
print("INVALID")
def split_to_digits(card):
return [int(i) for i in str(card)]
#Store every other digit into a list
everyotherdig = split_to_digits(card[-2::-2])
allotherdig = split_to_digits(card[-1::-2])
#Loop through string to apply Luhn's algorith
for i in everyotherdig:
if everyotherdig[i] > 5:
sum = split_to_digits(everyotherdig[i]) * 2
else:
sum1 = everyotherdig[i] *2
print(f"{sum}")
I managed to successfully get user input and get the card digits that i needed. Now i need to apply Luhn's algorithm to calculate whether the card number is valid. In order to do so i need to multiply every other digit by 2, starting with the number’s second-to-last digit, and then add those products’ digits together. Add the sum to the sum of the digits that weren’t multiplied by 2.
That sounds like a regular global-local variable mistake. In Python, unless you say that a variable is global, when you set a variable Python assumes it is local and not defining it in a function will cause 'not defined' problems. For example;
To declare a variable as global, you use
inside the function.
You should not use 'sum' as a variable name, because that is a builtin function.