2017-08-07 21 views
0

我不明白這個簡單的代碼:的Python:重試,直到一些變化

#!/usr/bin/env python 
# -*- coding: utf-8 -*- 

import time 

for val in "cacatcaca": 
    try: 
     if val == "c": 
      print(val) 
      time.sleep(0.5) 
     if val == "a": 
      print(val) 
      time.sleep(0.5) 
    except val == "t": 
     print('We are stock in the letter T') 
     time.sleep(0.5) 
     continue 

它給我的結果:

​​

而我想有是讓股票在't'直到時間的盡頭:

c 
a 
c 
a 
We are stock in the letter T 
We are stock in the letter T 
We are stock in the letter T 
... 
... 
... 

我的目標是當我收到一個重用爲谷歌API代碼。

我想繼續下去,並嘗試JSON響應,直到我得到不同的東西。

回答

1

此代碼將打印「我們在字母t的股票」直到時間結束。

import time 

for val in 'cacatcaca': 
    if val == 'c' or val == 'a': 
     print(val) 
     time.sleep(0.5) 
    elif val == 't': 
     while val == 't': 
      print('We are stock at letter t') 
0

您使用try-catch塊錯在這裏。

你應該把你的所有條件,if-else語句在try塊 如果有任何異常,然後打印這些。

for val in "cacatcaca": 
    try: 
     if val == "c": 
      print(val) 
      time.sleep(0.5) 
     elif val == "a": 
      print(val) 
      time.sleep(0.5) 

     elif val=="t": 
      print('We are stock in the letter T') 
      time.sleep(0.5) 

    except Exception as e: 
     print(e) 
     continue 
0

對於可重複使用的設計,我更願意使用基於這樣的代碼的解決方案:

def fetch_google_api_until_works(*args, **kwargs): 
    ok = False 
    while not ok: 
     response = legacy_fetch_google_api(*args, **kwargs) 
     ok = response.get('status', False) != 'OVER_QUERY_LIMIT' 
     if not ok: 
      time.sleep(0.5) 
    return response 

在您的應用程序代碼,然後使用fetch_google_api_until_works

相關問題