python - 循环内的调用函数在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() 查找并删除重复条目,因为它在循环内停止。我每次迭代都运行这个函数。我需要再次调用该函数并删除所有重复项。
代码没有错误,逻辑上我犯了错误。那是寻求帮助的请求。
解决方案
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
>>>
推荐阅读
- c++ - 在 Win32 API 中指定两次 LWA_COLORKEY
- swift - SwiftUI 春季计时似乎与 UIKit 春季计时不匹配
- google-kubernetes-engine - 从 docker hub 存储库中提取图像,使用的正确 url 是什么
- c - 这如何清除输入缓冲区?
- r - 为 R CMD 检查处理远程依赖项的正确方法是什么?
- dataframe - Julia 数据框中具有列名的控制流
- html - 下拉粘性导航栏的问题
- javascript - jquery.vmap.js 错误:错误:未捕获的类型错误:无法读取未定义的属性(读取“setFill”)
- plsql - PL/SQL。是否可以使用 SELECT INTO from table dual?
- vue.js - 使用 Vuex 和 Onboard.js 的最大调用堆栈大小超出错误