我的python代码有问题。我是python的初学者。
\
错误说它是def gen_qr_text(acc_id,amount):
pp_acc_id = ""
pp_amount = ""
pp_chksum = ""
if len(acc_id) == 15:
pp_acc_id = "0315" + acc_id
elif acc_id.length() == 13:
pp_acc_id = "0213" + acc_id
elif acc_id.length() == 10:
pp_acc_id = "01130066" + acc_id.substring(1)
else:
return "null"
if not amount:
pp_amount = format("54%02d%s", amount.length(), amount)
pp_str = "00020101021129370016A000000677010111"
+ pp_acc_id
+ "5303764"
+ pp_amount
+ "5802TH"
+ "6304"
pp_chksum = crc16.checksum(pp_str);
pp_str += pp_chksum;
return pp_str
。这段代码有什么问题。顺便说一句,我将代码从java转换为python。这是我的代码中的一切吗?我在这里编辑我的代码,但仍有一些错误
答案 0 :(得分:2)
Python就是所谓的“空格敏感”:它是如何缩进的。例如,它期望if
- 子句内的内容在下面缩进该语句:
if True or False:
execute_this_function()
这不起作用:
if True or False:
execute_this_function()
这同样适用于return
语句:它们应该在它们适用的函数内部,即您从以下位置返回:
def my_method():
return True
同样,这不起作用并引发你得到的错误:
def my_method():
return True
因此,解决方案是确保您的return
缩进正确。当然,这同样适用于其余代码!
修改根据OP的修改,这是您需要的缩进;我还修复了你从Java复制的.length()
,似乎:
def gen_qr_text(acc_id,amount):
pp_acc_id = ""
pp_amount = ""
pp_chksum = ""
if len(acc_id) == 15:
pp_acc_id = "0315" + acc_id
elif len(acc_id) == 13:
pp_acc_id = "0213" + acc_id
elif len(acc_id) == 10:
pp_acc_id = "01130066" + acc_id.substring(1)
else:
return "null"
if not amount:
pp_amount = format("54%02d%s", len(amount), amount)
pp_str = "00020101021129370016A000000677010111"
+ pp_acc_id
+ "5303764"
+ pp_amount
+ "5802TH"
+ "6304"
pp_chksum = crc16.checksum(pp_str);
pp_str += pp_chksum;
return pp_str
答案 1 :(得分:2)
您需要正确缩进代码。根据您的问题,我猜这会解决您的问题:
import crc16
def gen_qr_text(acc_id,amount):
pp_acc_id = ""
pp_amount = ""
pp_chksum = ""
if len(acc_id) == 15:
pp_acc_id = "0315" + acc_id
elif acc_id.length() == 13:
pp_acc_id = "0213" + acc_id
elif acc_id.length() == 10:
pp_acc_id = "01130066" + acc_id.substring(1)
else:
return "null"
if not amount:
pp_amount = format("54%02d%s", amount.length(), amount)
pp_str = "00020101021129370016A000000677010111" + pp_acc_id + "5303764" + pp_amount + "5802TH" + "6304"
pp_chksum = crc16.checksum(pp_str);
pp_str += pp_chksum;
return pp_str