简体   繁体   English

为了在Python 2.7中工作,我需要在代码中进行哪些修改?

[英]What do I modify in the code in order for it to work in Python 2.7?

 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. 这适用于Python 3.5。 What do I modify in order for it to work in Python 2.7? 我要对其进行哪些修改才能使其在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: raw_input()替换input()并更改对print语句的打印函数调用,或者您可以按照@BrenBarn的建议从__future__导入print_function ,例如:

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. 如果要使相同的脚本在Python 2.x和Python 3.x中都能工作,建议您使用“ six”模块和以下代码。 (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.")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM