2

Let's say i have some code written in Python 2.7 this code relies on one if statement being true and then uses another if condition and another depending on if both end up conditions being true can i continue to do this forever in my code or is there a limit? and is there anyway i can do this any better?

#!/usr/bin/python
import os
if os.path.isfile('/tmp/EXAMPLE.txt'):
    if os.path.getsize('/tmp/EXAMPLE.txt') == 0:
        if os.access('/tmp/EXAMPLE.txt', os.W_OK) == True:
            DATA = open('/tmp/EXAMPLE.txt', 'w')
            if DATA.mode == 'w':
                DATA.write('DATA')
                DATA.close()
                DATA = open('/tmp/EXAMPLE.txt', 'r')
                if DATA.mode == 'r':
                    if 'DATA' in DATA.read():
                        print 'File size is no longer zero'
                    else:
                        print 'Data failed to write'
                else:
                    print 'File could not be read from'
            else:
                print 'File could not written to'
        else:
            print 'File does not have write permissions'
    else:
        print 'File has data already'
else:
    print 'File does not exist'
Jeff Boils
  • 23
  • 5
  • Related to your second question: https://stackoverflow.com/questions/12265451/ask-forgiveness-not-permission-explain –  Oct 05 '19 at 17:34
  • It's more common in Python to work with exceptions – Olvin Roght Oct 05 '19 at 17:35
  • I don't know the answer and it's a good question in principle, but just saying, this isn't a smart and readable way to write this code (especially the else statements who are difficult to attach to their condition) – Ofer Sadan Oct 05 '19 at 17:35
  • 1
    There is, I believe, a limit, but well designed code would never come close to reaching it. It's only really an issue for machine-generated code (which doesn't care about readability). – chepner Oct 05 '19 at 17:36

1 Answers1

1

You can keep on going - but you shouldn't. This code is unreadable. Instead you should invert the if checks. For example if your code only works if the path is a file then instead of this:

if os.path.isfile('/path/to/file'):
   # rest of code

You can do this:

if not os.path.isfile('/path/to/file'):
    # error handling, reporting, change of control etc.
# rest of code

Here's some of the code from your question 'inverted' in this way:

#!/usr/bin/python
import os
import sys

if not os.path.isfile('/tmp/EXAMPLE.txt'):
    print('File does not exist')
    sys.exit(1)
if os.path.getsize('/tmp/EXAMPLE.txt') != 0:
    print('File has data already')
    sys.exit(1)

if os.access('/tmp/EXAMPLE.txt', os.W_OK) == False:
    print('File does not have write permissions')
    sys.exit(1)
# rest of the code
rdas
  • 20,604
  • 6
  • 33
  • 46
  • What do you mean by invert? Yeah i agree the code isn't very pleasant on the eyes and is hard to keep a grasp on what is going where however this was the only way i know how to use multiple if conditions together besides chaining them together i would have used and/or instead of these repeated conditions however the project i am working on preforms multiple checks on separate lines and redirects execution flow based on the output – Jeff Boils Oct 05 '19 at 17:52
  • Which to my knowledge is keeping me from chaining them together or using other operators such as and/or i wrote the given code as a example for the question i was asking it is not related to my project and i can not give that code away just yet i am still new to Python and programming in general so excuse my bad code i am working on getting better at writing more readable code – Jeff Boils Oct 05 '19 at 17:54
  • That being said the code works i executed it within a Python shell before posting this question. I am looking into other control statements and operators i am also going to rewrite my example with the mentioned adjustments and see how it executes and rewrite my project with the changes. If you have any further reading about this question or Python in general please link me – Jeff Boils Oct 05 '19 at 17:58
  • I've made the changes to your code and posted in the answer. Check if it makes sense now. – rdas Oct 05 '19 at 17:59
  • In your code i don't see any else conditions are they needed? Or will python just pass to the next statement if that statement fails? – Jeff Boils Oct 05 '19 at 18:10
  • I understand what you mean by inverted now basically you mean instead of expecting the output to be true expect it to be false and redirect based on that and execute the code which is supposed to run if all are true if the above statements fails? – Jeff Boils Oct 05 '19 at 18:11
  • `sys.exit` ends the program so later code doesn't execute – rdas Oct 05 '19 at 18:11
  • I am new to Python and programming in general so excuse my noob questions i know that the if statements are used for if a condition is supposed to match the expected outcome otherwise the else statement is executed and a elif is used if both conditions fail my question is within your code you aren't using else statements so are they not needed? If i understand right your code is executing if the if statements fail – Jeff Boils Oct 05 '19 at 18:14
  • I know about sys.exit i want to know if Python continues the program execution even without a else statement? – Jeff Boils Oct 05 '19 at 18:14
  • Yes. You can think of `if` statements that don't have a corresponding `else` as "optional code" - python just picks up from the next line if there is no `else` – rdas Oct 05 '19 at 18:16
  • Your program is checking to see if the file does not exist therefore the if not and if it does not exist then exit using sys.exit the 1 in () is the exit status code and seeing if the file size is greater than 0 and then exiting if so and finally checking the file does not have write permissions and then exiting if it does not and then executing rest of the code – Jeff Boils Oct 05 '19 at 18:16
  • I understand the code i just needed a explaining of the else – Jeff Boils Oct 05 '19 at 18:17
  • If i understand correctly the if statements with a if and else are expected to execute and the if statements without a else are just there as you put it optional code meaning it will execute if the if statement is needed otherwise will just pass to the rest of the code? So in my code i need to use the inverted way of making sure it won't give the expected output of being false and then executing the code after the above statements fail and program execution is still going – Jeff Boils Oct 05 '19 at 18:19