I’m trying to make a function retry if an input isn’t 1 or 2, using the
“retry” package. I can’t seem to get it to work. I just started with
Python a few days ago and I need urgent help with this. (I’m doing it
for a school project due in 11 hours.) What am I doing wrong and is
there a better/easier way to retry a function?
The code below is helpful (essential even) but it would help to also
have a transcript of the errors you get.
Assorted remarks inline below:
from retry import retry
I assume this is what you’re using:
https://pypi.org/project/retry/
first value is the exception, tries is the amount of times the function retries, delay is the amount of time between each retry
@retry(ValueError, tries=3, delay=2)
This looks correct.
def gooo():
‘’‘Retry’‘’
This function does not seem to do anything. The purpose of the retry
decorator if to cause gooo to retry if a ValueError occurs within it. If
your function does nothing, there’s nothing to retry.
select = int(input(“Gibe me number 1 or 2:”))
if select == 1:
digitboy = “Thanks for 1!”
elif select == 2:
digitboy = “Thanks for 2!”
else:
raise ValueError
gooo(ValueError)
The indentation above looks wrong. I imagine it should read:
select = int(input("Gibe me number 1 or 2:"))
if select == 1:
digitboy = "Thanks for 1!"
elif select == 2:
digitboy = "Thanks for 2!"
else:
raise ValueError
gooo(ValueError)
print(digitboy)
I presume this is meant to print digitboy after some retries.
For this to be meaningful, the input and checking of the value should be
inside the gooo() function. That way gooo() can be retried a few
times.
Then there’s the end bit where there’s no 1 or 2:
raise ValueError
gooo(ValueError)
This isn’t right. Exceptions are instances of various exception
classes/types. ValueError is such a class. So the raise probably wants:
raise ValueError("expected 1 or 2, got %s" % select)
to raise a ValueError instance with a meaningful message.
It looks to me like gooo() is meant to ask for the 1 or 2 and return the
value received. So (a) the input() code above needs to be inside the
function and (b) it needs to return that value. it looks like the
digitboy variable is for use outside the function. So your function
might look like:
@retry(ValueError, tries=3, delay=2)
def gooo():
select = int(input("Gibe me number 1 or 2:"))
if select == 1 or select == 2:
return select
raise ValueError
and outside you’d call gooo() to obtain the value:
value = gooo()
which would do all the retrying. Then use your if-statement to set the
digitboy variable according to the value you get back from gooo().
Cheers,
Cameron Simpson cs@cskk.id.au