The variable defined in if cannot be referenced when if is false.

for bt_con in bentie_content:  -sharp 
    bt_con = re.sub("<.*?>", "", bt_con)
    bt_con = re.sub("\s", "", bt_con)
    if bt_con != "":
        print(bt_con)
        bt_cons = [bt_con]
if not huifu_id:
    huifu_id = [""]
date_list = bentie_id + bentie_uid + bentie_tx + bentie_nickname + bentie_creattime + bt_cons + huifu_id
In the

code, when I assign a value to date_list , I refer to the bt_cons variable, but when the result of the if condition is false, is there no bt_cons variable?

tried to add else , neither continue nor break. Later, I wanted to move this assignment to if, but. There is another if to judge, and the result of the judgment is to be assigned.

I would like to ask how to deal with this situation. The purpose is to change it to a list when bt_con is not empty. If it is empty, this item will skip

.
Oct.22,2021

the conventional solution is to give the variable an initial value before if, for example:

bt_cons = []
if bt_con != '':
  bt_cons = [bt_con]
  

of course, you can also use python's binary expression to simplify the statement:

bt_cons = [bt_con] if bt_con != '' else []

  

itself bt_cons is not defined elsewhere (initialization), but only initialized when if takes effect. Of course, if if does not work, it cannot be referenced. You need to deal with this in the process to ensure that it is initialized, and then there will be no mistakes. The
method is the two methods introduced by i38me. Note that you are judging two different things at this time, bt_con rather than bt_cons,.

of course, even your code can also follow the following processing to ensure that it does not report errors:

for bt_con in bentie_content:  -sharp 
    bt_con = re.sub('<.*?>', '', bt_con)
    bt_con = re.sub('\s', '', bt_con)
    if bt_con != '':
        print(bt_con)
        bt_cons = [bt_con]
    else :
        bt_cons = []
if not huifu_id:
    huifu_id = ['']

date_list = bentie_id + bentie_uid + bentie_tx + bentie_nickname + bentie_creattime + bt_cons + huifu_id
Menu