首页 > 解决方案 > 循环内的调用函数在python中不起作用

问题描述

该函数在循环内工作正常

import random


def hello():
    count = 0
    while count < 5:
        count = count + 1
        print(str(count + random.randint(1, 30)) + " hello I am inside")
        break


count = 0
while count < 5:
    count = count + 1
    print(str(count) + " Outside")
    hello()

打印输出:

K:\Project\Python\Campaign\venv\Scripts\python.exe K:/Project/Python/Campaign/functionInsideLoop.py
1 Outside
12 hello I am inside
2 Outside
30 hello I am inside
3 Outside
19 hello I am inside
4 Outside
6 hello I am inside
5 Outside
23 hello I am inside

Process finished with exit code 0

但是当我尝试运行它时,函数并没有重复调用。我想输出 1 hello I am inside 并递增 1、2、3、4、5

def hello():
    count = 0
    while count < 5:
        count = count + 1
        print(str(count) + " hello I am inside")
        break


count = 0
while count < 5:
    count = count + 1
    print(str(count) + " Outside")
    hello()

打印输出:

K:\Project\Python\Campaign\venv\Scripts\python.exe K:/Project/Python/Campaign/functionInsideLoop.py
1 Outside
1 hello I am inside
2 Outside
1 hello I am inside
3 Outside
1 hello I am inside
4 Outside
1 hello I am inside
5 Outside
1 hello I am inside

Process finished with exit code 0

这个想法是一次又一次地在循环中调用一个函数。我发现当我在循环内使用 break 函数并在另一个循环外调用它时,函数没有改变。

如果我给你一个真实的例子:

import sqlite3

connection = sqlite3.connect('../miracle.db')
cursor = connection.cursor()
cursor.execute("SELECT* FROM all_fb_user")


def remove_duplicate():
    records = cursor.fetchall()
    for record in records:
        singleRecord = record
        # Find All Duplicate
        cursor.execute("SELECT * FROM all_fb_user GROUP BY user_url HAVING COUNT(*) > 1;")
        records = cursor.fetchall()
        try:
            for pk in records[1]:
                duplicate_pk = (records[1])[4]
                print(duplicate_pk)
                cursor.execute("DELETE FROM all_fb_user WHERE PK=?", (duplicate_pk,))
                break
            break
        except:
            print(" There are no Duplicate in the list")
            break


count = 0
while count < 10:
    count = count + 1
    print(count)
    remove_duplicate()

connection.commit()
connection.close()

remove_duplicate() 查找并删除重复条目,因为在循环内停止。我每次迭代都运行这个函数。我需要再次调用该函数并删除所有重复项。

代码没有错误,逻辑上我犯了错误。那是寻求帮助的请求。

标签: pythonsqlite

解决方案


break inside hello() 导致问题,将其删除,它将按如下方式工作。

>>> def hello():
...     count = 0
...     while count < 5:
...         count = count + 1
...         print(str(count) + " hello I am inside")
... 
>>> hello()
1 hello I am inside
2 hello I am inside
3 hello I am inside
4 hello I am inside
5 hello I am inside

并修改第二个如下:

>>> count = 0
>>> while count < 5:
...     count = count + 1
...     print(str(count) + " Outside")
...     if count == 1:
...         hello()
...     else:
...         break
... 
1 Outside
1 hello I am inside
2 hello I am inside
3 hello I am inside
4 hello I am inside
5 hello I am inside
2 Outside
>>> 

推荐阅读