#๐Ÿ”’ Is this overkill? Code Simplification

41 messages ยท Page 1 of 1 (latest)

rotund epochBOT
#

@sweet bison

Python help channel opened

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.

naive heath
#

A little.

#

It also has some bugs.

eternal juniper
#

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

naive heath
#

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 ๐Ÿ™

eternal juniper
#

True, if you're having to double check the result against the expected prompts anyways, then you don't need the regex

sweet bison
#

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

naive heath
naive heath
sweet bison
naive heath
#

So, our comments above any help?

sweet bison
#

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

naive heath
#

Regexps should almost always be a second choice. They're cryptic and brittle.

#

This is a bug: value.lower() == "yes" or "y"

#

!or-gotcha

rotund epochBOT
#
The 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.")
sweet bison
naive heath
sweet bison
eternal juniper
#

It's the return that's responsible for getting you out of this loop. The try/except has nothing to do with it

sweet bison
#

got it!

eternal juniper
#

a simple "if valid response, return" will be just fine

naive heath
#

Basicly this function:

  • loops until it gets yes or no
  • should return True for yes and False for no
#

try/except is for catching specific expected failures. You haven't got any of those here.

sweet bison
#

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): ")
naive heath
#

(we all write one of these at some point. I usually call mine ask.)

naive heath
#

since control returns from the function at return and doesn't continue past that you don't need the "else" stuff.

sweet bison
#

does it functionally parse faster like this if you were to use a timer module, or is it just a stylistic choice?

naive heath
#

Just style. There shouldn't be any timing changes at all, quite possibly.

#

Need to go AFK for a while.

sweet bison
#

I think ill leave it as is for my sake. I'll clean things up as I learn more!

rotund epochBOT
#
Python help channel closed for inactivity

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.