【问题标题】:Python while loop ( until data exist ) [closed]Python while循环(直到数据存在)[关闭]
【发布时间】:2018-06-15 10:06:17
【问题描述】:

我正在寻找使用 WHILE 循环或 FOR 循环的不同方法来解决我目前面临的问题。

我正在寻找待处理(检查)循环

我有发送请求并接收输出的代码,这是一个空字段或报告创建日期。

想法是做这样的事情:

WHILE generatedDate is None:
 run the script which gets information if it None
    IF generatedDate is not None
    Another bit of code which will download the report which just created

代码应该是这样的吗??

while x is None
#Do stuff
   if x is not None
   #Do other stuff

答案正是我想要的,抱歉没有提供完整的详细信息。

import time

#This part I made to access API and receive up to date JSON file
def get_data():
    data=None #Initially no data
    return data
#This section was modified to def download_report
def treat_data(data):
    #do the stuff when you got data, in your case download the report
    pass

#Check if data received
generatedData=get_data()

#Loop for pinging when data will be filled in.
while generatedData==None:

    #Pingin text
    print "waiting data"

    generatedData=get_data()

    #Wating time between checks
    time.sleep(0.25)


#download_report call after exiting the loop (after field become not empty)
treat_data(generatedData) #report generated

【问题讨论】:

  • 你有伪代码那么有什么问题
  • 应该是None 而不是in
  • @Roushan 我不知道如何编写实际代码。此代码中的斗争部分是“无”,如何创建将检查 1)数据不存在和 2)数据存在的代码。因为通常情况下,解决方案是这样的(当 x > 2),你的实际值会增加或减少。
  • whilemore on while 基本上是start here: .. SO 不是教授语言基础知识的教程网站。我们关心具体问题如果您已经在此站点和其他站点上进行了研究并且被卡住了。

标签: python loops for-loop while-loop do-while


【解决方案1】:

也许是这样的?

import time

#this function will return None if no data, and return the data if you got data
def get_data():
    #here we do stuff to verify if we got data
    data=None #we suppose there is no data
    return data

def treat_data(data):
    #do the stuff when you got data, in your case download the report
    pass

#check first if we got data
generatedData=get_data()

#then waiting until you get data
while generatedData==None:

    #check again if we got data
    print "waiting data"

    generatedData=get_data()

    #wait 0.25s between two check
    time.sleep(0.25)

#here we assume we got data (because we leave the while loop)
#so we treat the data
treat_data(generatedData)

由于我们没有实现 func get_data,这个脚本会返回:

waiting data
waiting data
waiting data
waiting data
waiting data
waiting data
waiting data
waiting data
waiting data
waiting data
waiting data
waiting data
waiting data
waiting data
waiting data
waiting data
waiting data
waiting data
waiting data
waiting data
[...]

【讨论】:

  • 谢谢你。这正是我们想要的。
【解决方案2】:

while 应该是小写的并且它应该有一个类似的条件 而(var == true): ...

【讨论】:

    猜你喜欢
    • 2020-09-29
    • 1970-01-01
    • 2018-08-15
    • 2020-05-27
    • 1970-01-01
    • 1970-01-01
    • 2016-03-15
    • 2016-03-14
    • 2021-05-17
    相关资源
    最近更新 更多