【问题标题】:What do I modify in the code in order for it to work in Python 2.7?我应该在代码中修改什么以使其在 Python 2.7 中工作?
【发布时间】:2016-11-18 04:20:41
【问题描述】:

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 中工作,我需要修改什么?

【问题讨论】:

    标签: python python-2.7 python-3.5


    【解决方案1】:

    input() 替换为raw_input() 并将打印函数调用更改为打印语句,或者您可以按照@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.")
    

    【讨论】:

    • 打印调用实际上会按原样工作,因为括号只是作为多余的分组。但更好的解决方案是把from __future__ import print_function放在开头,让你可以使用Python 3风格的打印功能。
    【解决方案2】:

    如果您希望相同的脚本同时在 Python 2.x 和 Python 3.x 中工作,我建议使用“six”模块和以下代码。 (请注意,添加的前两行是我所做的唯一更改。)

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-06-20
      • 1970-01-01
      • 2010-11-08
      • 2018-01-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-12
      相关资源
      最近更新 更多