Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
TO ELSE OR NOT TO ELSE?
#4
(Apr-27-2019, 02:04 AM)rxndy Wrote: Should we always use else statements?
Definitely not. The use of else will depend on your use case. I will open a bracket - some recommend always using else, but not in the context you have in mind, but as a way to show that programmer has considered all possible outcomes/did not forget the else (some branch). See this recent discussion https://python-forum.io/Thread-Just-comp...1#pid78691 that touches the topic.

Your examples are mix of input validation/type checking and regular branching. Also each programming language has it patterns (and tools) and one should use these.

As to error handling - would you handle all errors, which errors would you handle and how would you handle them also depends on your use case. For example in a software for end user you would make reasonable effort to handle at least basic errors - for example you don't want user to get error for invalid input. How you would handle it is another question - I would come to that shortly. On other hand if you write a package that would be used by other programmers in their code most probably you would want to propagate the errors so that they handle them themselves the way they want, i.e. you don't want to restrict them with your logging for example (for example think of python wrapper/sdk around some API).

Regarding error handling python has try/except/else/finally so for error handling you would use this construct. Note it has else and finally, but they are optional. This construct has advantage over using if/else especially in cases where race conditions are possible (think of checking that file exists before deleting, but with if/else it can be deleted by some other procees between you check it exists and actually trying to delete it). It's an implementation of python philosophy - Easier to ask for forgiveness than permission (EFAP). See also https://docs.quantifiedcode.com/python-a...files.html

As to type checking - I would say that more often than not type checking is not needed and even discouraged by python community as anti-pattern. That is so called duck typing. And if you really have to do type checking it's recommended to use isinstance() instead of type().

Let's return to your examples. How would you make sure user has supplied integer
def get_int(prompt=''):
    while True:
        user_input = input(prompt)
        try:
            return int(user_input)
        except ValueError:
            # you can log here
            print('This is not a valid input. Please enter an integer')

my_int = get_int('Please enter an integer number: ')
print(f'You have entered {my_int}')
Output:
Please enter an integer number: a This is not a valid input. Please enter an integer Please enter an integer number: This is not a valid input. Please enter an integer Please enter an integer number: 1.2 This is not a valid input. Please enter an integer Please enter an integer number: 5 You have entered 5 >>>
Your other two examples are actually regular branching of your program flow and using else might be warranted depending on what you want to do. Let's look at your last example.
You read some value from a sensor and process it. It's possible to have 3 scenarios:

if reading higher than some value - do A
if value below that value - do B but also send a message/turn on alarm, log, etc. Here B can be also "do nothing"
if value below that value - still do A, but also send a message/turn on alarm/log, etc.

if we have 1 and 2 in pseudo-code you would do

if reading > some_value:
    do A
else:
    do B
    send message/alarm/log, etc.
but in case 1 and 3 you can do

if reading > some_value:
    do A
else:
    do A
    send message/alarm/log, etc.
OR skip the else
if reading <= some_value:
    send message/alarm/log, etc.
do A
in my view the second one is better and I would go for it.

Sorry if my answer may be a little bit chaotic, but it's because in your question you mix a lot of different concepts/paradigms/code patterns
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply


Messages In This Thread
TO ELSE OR NOT TO ELSE? - by rxndy - Apr-27-2019, 02:04 AM
RE: TO ELSE OR NOT TO ELSE? - by nilamo - Apr-29-2019, 10:03 PM
RE: TO ELSE OR NOT TO ELSE? - by rxndy - Apr-30-2019, 02:11 AM
RE: TO ELSE OR NOT TO ELSE? - by buran - Apr-30-2019, 07:13 AM
RE: TO ELSE OR NOT TO ELSE? - by rxndy - Apr-30-2019, 11:42 PM

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020