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.")

这适用于Python 3.5。我要修改什么才能在Python 2.7中工作?
答案 0 :(得分:2)
将input()
替换为raw_input()
并将打印函数调用更改为print语句,或者您可以从print_function
导入__future__
,如@BrenBarn所示,例如:
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.")
答案 1 :(得分:1)
如果你想在Python 2.x和Python 3.x中使用相同的脚本,我建议使用“six”模块和以下代码。 (请注意,前两个添加的行是我所做的唯一更改。)
var vehicles = [string]()
let mustang = Car() // car is a class name
mustang.brandName = "Ford"
mustang.modelName = "Mustang" // string type
mustang.modelYear = 1968
mustang.isConvertibible = true
mustang.isHatchback = false
mustang.hasSunroof = false // bool type
mustang.numberOfDoors = 2 // int type
mustang.powerSource = "gas engine"
// Add it to array
vehicles.append(mustang.brandName)
vehicles.append(mustang.modelName)
vehicles.append(mustang.modelYear) // Error: int type not supported
vehicles.append(mustang.isConvertibible) // Error: bool type not supported
vehicles.append(mustang.brandName)
vehicles.append(mustang.brandName)