#๐ Is this overkill? Code Simplification
41 messages ยท Page 1 of 1 (latest)
@sweet bison
Remember to:
- Ask your Python question, not if you can ask or if there's an expert who can help.
- Show a code sample as text (rather than a screenshot) and the error message, if you've got one.
- Explain what you expect to happen and what actually happens.
:warning: Do not pip install anything that isn't related to your question, especially if asked to over DMs.
I don't think it's overkill to be using regex to handle the prompt, but there's some other issues with the way it's structured
I'd be just downcasing the response and testing value.strip().lower() in ('y', 'yes')
I wouldn't bother with the regexp.
It should just return True or False IMO, not a string.
Never use a bare except:, and if you're going to catch an exception (and ignore it!) at least print out what it was ๐
True, if you're having to double check the result against the expected prompts anyways, then you don't need the regex
sorry yall. discord was being dumb and double posted
Hiya everyone. I'm picking back up with python after not touching it for over 5 years. I'm relearning using forums and that such whilst forcing myself not to use AI. My question is such. Is the code below overkill for what I want it to do, or is this the most robust way to do this.
#reusable case-insensitive yes/y or no/n checker that returns a value of yes or no back
def yes_no(prompt):
pattern = re.compile(r'\b(yes|no|y|n)\b', re.IGNORECASE)
while True:
try:
value = pattern.search(input(prompt))
value = value.group()
if not value: #Returns if it receives no value or None as the value
print("Invalid option. Please type Y(es)/N(o): ")
else:
if value.lower() == "yes" or "y":
return str("yes")
elif value.lower() == "no" or "n":
return str("no")
except:
print("An unknown error occured. Please type Y(es)/N(o): ")
heres the origianly prompt
I dont know how to delete the other thread
Closing it is enough. All good.
We've seen other people do this. Sounds like discord's a bit silly.
phew! glad it wasn't just me. I'll adjust code accordingly.
So, our comments above any help?
yea! I go a little overboard with regex because it only passes things through if it passes the test. I always forget that there are other ways to test things XD
Regexps should almost always be a second choice. They're cryptic and brittle.
This is a bug: value.lower() == "yes" or "y"
!or-gotcha
When checking if something is equal to one thing or another, you might think that this is possible:
# Incorrect...
if favorite_fruit == 'grapefruit' or 'lemon':
print("That's a weird favorite fruit to have.")
While this makes sense in English, it may not behave the way you would expect. In Python, you should have complete instructions on both sides of the logical operator.
So, if you want to check if something is equal to one thing or another, there are two common ways:
# Like this...
if favorite_fruit == 'grapefruit' or favorite_fruit == 'lemon':
print("That's a weird favorite fruit to have.")
# ...or like this.
if favorite_fruit in ['grapefruit', 'lemon']:
print("That's a weird favorite fruit to have.")
thanks! i would have never known
In short:
- fix that or bug
- drop the try/except entirely
- drop the regexp entirely
- return
TrueorFalse
would be my initiali recommendations.
if i drop the try/except will it still loop infinitely until y,yes,n,no is passed in as an input
It's the return that's responsible for getting you out of this loop. The try/except has nothing to do with it
got it!
a simple "if valid response, return" will be just fine
Sure. Is that unwanted?
Basicly this function:
- loops until it gets yes or no
- should return
Truefor yes andFalsefor no
try/except is for catching specific expected failures. You haven't got any of those here.
Better?
def yes_no(prompt):
while True:
value = input(prompt)
if value.strip().lower() in ('y', 'yes'):
return True
elif value.strip().lower() in ('n', 'no'):
return False
else:
print("Invalid option. Please type Y(es)/N(o): ")
(we all write one of these at some point. I usually call mine ask.)
You could shorten it slightly:
def yes_no(prompt):
while True:
value = input(prompt)
if value.strip().lower() in ('y', 'yes'):
return True
if value.strip().lower() in ('n', 'no'):
return False
print("Invalid option. Please type Y(es)/N(o): ")
A stylistic choice, not a criticism.
since control returns from the function at return and doesn't continue past that you don't need the "else" stuff.
does it functionally parse faster like this if you were to use a timer module, or is it just a stylistic choice?
Just style. There shouldn't be any timing changes at all, quite possibly.
Need to go AFK for a while.
I think ill leave it as is for my sake. I'll clean things up as I learn more!
This help channel has been closed. Feel free to create a new post in #1035199133436354600. To maximize your chances of getting a response, check out this guide on asking good questions.