2

I am learning how to use do not repat yourself principle (https://en.wikipedia.org/wiki/Don%27t_repeat_yourself) in Python.

See my block of code below:

        for key, value in my_dictionary.items():
            if "," in value:
                if key != value:
                    raise ValueError(f"This is my error !")
            else:
                if key != value + ",00":
                    raise ValueError(f"This is my error !")

You can see that I repeat the part raise ValueError(f"This is my error !") two times. Is it posible to use it only once? I tried to use for/else method, but I got lost. Thank you very much for help.

2
  • 2
    You're interpreting DRY far too literally. It's about redundant data storage; it doesn't literally mean "never type the same sequence of characters ever". Commented Jun 9, 2021 at 13:44
  • if key not in (value, value + ',00'): raise ...…? Commented Jun 9, 2021 at 13:44

1 Answer 1

3

You could use

for key, value in my_dictionary.items():
    if ("," in value and key != value) or (key != value + ",00"):
        raise ValueError(f"This is my error !")
    
    # everything seems to be fine
    # do sth. useful here
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.