No, you cannot do that. That's just the way Python has its syntax. Once you exit a try-block because of an exception, there is no way back in.
What about a for-loop though?
funcs = do_smth1, do_smth2
for func in funcs:
try:
func()
except Exception:
pass # or you could use 'continue'
Note however that it is considered a bad practice to have a bare except. You should catch for a specific exception instead. I captured for Exception because that's as good as I can do without knowing what exceptions the methods might throw.
No, you cannot do that. That's just the way Python has its syntax. Once you exit a try-block because of an exception, there is no way back in.
What about a for-loop though?
funcs = do_smth1, do_smth2
for func in funcs:
try:
func()
except Exception:
pass # or you could use 'continue'
Note however that it is considered a bad practice to have a bare except. You should catch for a specific exception instead. I captured for Exception because that's as good as I can do without knowing what exceptions the methods might throw.
While the other answers and the accepted one are correct and should be followed in real code, just for completeness and humor, you can try the fuckitpy ( https://github.com/ajalt/fuckitpy ) module.
Your code can be changed to the following:
@fuckitpy
def myfunc():
do_smth1()
do_smth2()
Then calling myfunc() would call do_smth2() even if there is an exception in do_smth1())
Note: Please do not try it in any real code, it is blasphemy
Videos
I want the loop to skip to the next iteration when ValueError is raised. Raising error there is a must. I try to put continue operator in except block but it's wrong. Please help me, thanks
NList = []
def isInt(N):
try:
int(N)
return True
except:
return False
try:
while True:
N = input("Enter an positive interger: ")
if N == 0: break
NList.append(N)
if not isInt(N):
raise ValueError("It's not an interger")
int(N)
if N < 1:
raise ValueError("It's not positive")
except ValueError as e:
print(e)
continueI have read numerous StackOverflow threads about looping during try/except statements, using else and finally, if/else statements, and while statements, but none of them address what I want. That or I don't know how to utilise that information to get what I want done.
Basically, I am trying to get adjusted closing stock prices for various companies on a given date. I pasted some dummy data in the code block below to demonstrate (NOTE: you'll have to install pandas and pandas_datareader to get the dummy code to run). The `get_stock_adj_close` function returns the adj_close price given a ticker and date. The `dummy_dataframe` contains 4 companies with their tickers and random dates. And the `add_days` function takes a date and adds any number of days. I would like to append the adjusted close stock prices for each company in the dataframe on the listed date into the `stock_prices` list.
Because the yahoo stock price database isn't that reliable for older entries and because some dates fall on days when the market is closed, whenever a price isn't available it raises a `KeyError: 'Date'`. Thus, what I would like to do is keep adding days indefinitely until it finds a date where a price does exist. The problem is it only adds the day once and then raises the same `KeyError`. I want it to keep adding days until it finds a day where the database has a stock price available and then return back to the dataframe and keep going with the next row. Right now the whole thing breaks on the first GM date (fourth row), which raises the `KeyError` and the fifth row/second GM date is ignored. Any help is appreciated!
Dummy data:
from datetime import datetime, date, timedelta
import pandas as pd
import pandas_datareader as pdr
from dateutil.relativedelta import relativedelta
def add_days(d, num_days):
return d + timedelta(days=num_days)
def get_stock_adj_close(ticker, chosen_date):
stock_df = pdr.get_data_yahoo(ticker, start = chosen_date, end = chosen_date)
return stock_df.iloc[0]['Adj Close']
d = {'TICKER': ['AMD','AMD','CHTR','GM'], 'DATE': [datetime(2020,2,4), datetime(2019,2,8),datetime(2019,1,31), datetime(2010,4,7)]}
dummy_dataframe = pd.DataFrame(data=d)
stock_prices = []
for i, row in dummy_dataframe.iterrows():
given_date = row['DATE']
try:
stock_price = get_stock_adj_close(row['TICKER'], given_date)
print(stock_price)
stock_prices.append(stock_price)
except KeyError:
given_date = add_days(given_date,1)
stock_price = get_stock_adj_close(row['TICKER'], given_date)
stock_prices.append(stock_price)
print(stock_prices)I have a function that loops over a list of IDs and makes an API query for each ID in the list. This list is 600ish IDs long. Occasionally I run into the issue where my API token will expire before the function completes. In another post I believe i addressed that issue by creating a function that should ensure my API token doesnt expire. What I have is this:
def query_form_dynamic_data(oauth, token) -> list:
# Loop through the list of form IDs and pass the ID as a variable to the GraphQL query
form_id_list = query_pif_id(oauth, token)
dynamic_data = []
try:
token = ensure_token(oauth, token)
transport = create_transport_protocol(token, proxies)
client = create_graphql_client(transport)
for key, val in enumerate(form_id_list):
query = gql(""" query goes here """)
result = client.execute(query, variable_values=val)
result = result["documents"]
dynamic_data.append(result)
except TokenExpiredError as err:
token = ensure_token(oauth, token)
return dynamic_dataWhat im hoping this does is by calling my ensure_token function before the query, if the token has expired, it would refresh the token. But if it expires in the middle of my loop then im screwed. I know it throws the TokenExpiredError if that happens and then it'll rerun my ensure_token function to get a new key, but will the contents of my try block continue at that point?