For循环而不循环if语句

时间:2019-11-21 15:01:50

标签: python-3.x for-loop

这是我的代码:

import openpyxl


wb = openpyxl.load_workbook("Bok1.xlsx", data_only=True)
ws = wb["Blad1"]

n = 0

for row in ws['A1:A100']:
    for cell in row:
        if cell.value == "Konto":
            for hej in range(13):
                n+=1
                konto = cell.offset(row=n).value
                if konto == None or isinstance(konto, str) == True:
                    pass
                else:
                     if konto == 306888 or konto == 306889:
                        #derp = input("derpderpderp?: ")
                        #if derp == "y":
                            if konto == 306888 or konto == 306889:
                                kst = cell.offset(row=n, column = 1).value
                                proj = cell.offset(row=n, column = 2).value
                                vht = cell.offset(row=n, column = 3).value
                                motp = cell.offset(row=n, column = 4).value
                                fin = cell.offset(row=n, column = 5).value
                                text = cell.offset(row=n, column = 8).value
                                belopp = cell.offset(row=n, column = 9).value
                                print(konto)
                                print(kst)
                                print(proj)
                                print(vht)
                                print(motp)

如代码中的#所示,我有一个“依赖”循环的输入。我如何编写此代码,以使它不会循环并要求每次迭代都输入?

1 个答案:

答案 0 :(得分:0)

我要做的是保持计数器:

n = 0
cnt=1         # counter

for row in ws['A1:A100']:
       # continue with your code

然后,当您输入内容时:

if cnt==1:
   derp = input("derpderpderp?: ")
   cnt += 1
   if derp == "y":
      #continue with your code

这样,您可以确保仅在初次输入时才进行输入。