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

這適用於Python 3.5。 我要對其進行哪些修改才能使其在Python 2.7中工作?

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

如果要使相同的腳本在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.")

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM