credit_num = input("Enter the credit card number: ").replace(" ", "") tot1 = 0 tot2 = 0 for i in credit_num[-1::-2]: tot1 += int(i) for i in credit_num[-2::-2]: tot2 += sum(int(x) for x in str(int(i)*2)) rem = (tot1 + tot2) % 10 if rem == 0: print("The entered numbers are valid.") else: print("The entered numbers are not valid.")
This works in Python 3.5. What do I modify in order for it to work in Python 2.7?
Replace input()
with raw_input()
and change the print function calls to print statements or you can import print_function
from __future__
as @BrenBarn suggests, eg:
from __future__ import division, print_function
credit_num = raw_input("Enter the credit card number: ").replace(" ", "")
tot1 = 0
tot2 = 0
for i in credit_num[-1::-2]:
tot1 += int(i)
for i in credit_num[-2::-2]:
tot2 += sum(int(x) for x in str(int(i)*2))
rem = (tot1 + tot2) % 10
if rem == 0:
print("The entered numbers are valid.")
else:
print("The entered numbers are not valid.")
If you want the same script to work in both Python 2.x and Python 3.x, I suggest using the "six" module and the following code. (Note that the first two added lines are the only change I've made.)
from __future__ import print_function
from six.moves import input
credit_num = input("Enter the credit card number: ").replace(" ", "")
tot1 = 0
tot2 = 0
for i in credit_num[-1::-2]:
tot1 += int(i)
for i in credit_num[-2::-2]:
tot2 += sum(int(x) for x in str(int(i)*2))
rem = (tot1 + tot2) % 10
if rem == 0:
print("The entered numbers are valid.")
else:
print("The entered numbers are not valid.")
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.