Understanding code


##

# Remove all of the comments from a Python file (ignoring the case where a comment

# character occurs within a string)

#

# Read the file name and open the input file

try:

        in_name = input("Enter the name of a Python file: ")

        inf = open(in_name, "r")

except:

# Display an error message and quit if the file was not opened successfully

        print("A problem was encountered with the input file.")

        print("Quitting...")

        quit()

# Read the file name and open the output file

try:

        out_name = input("Enter the output file name: ")

        outf = open(out_name, "w")

except:

# Close the input file, display an error message and quit if the file was not opened

# successfully

        inf.close()

        print("A problem was encountered with the output file.")

        print("Quitting...")

        quit()

try:

# Read all of the lines from the input file, remove the comments from them, and save the

# modified lines to a new file

        for line in inf:

# Find the position of the comment character (-1 if there isn’t one)

                pos = line.find("#")

# If there is a comment then create a slice of the string that excludes it and store it back

# into line

                if pos > -1:

                        line = line[0 : pos]

                        line = line + "\n"

# Write the (potentially modified) line to the file

                outf.write(line)        

# Close the files

        inf.close()

        outf.close()

except:

# Display an error message if something went wrong while processing the file

        print("A problem was encountered while processing the file.")

        print("Quitting...")

I don’t understand what this if statement does

if pos > -1:

position is the index of the #, if l am correct why are they checking if pos is greater than -1

The purpose of the code is written in the line after the double #

Thanks

As it says in this comment code

pos takes the value of -1 if the find() method cannot find the supplied character. If a character is found it returns the position, so by necessity if a position is found pos must have the value 0 or above i.e. pos > -1. Just an easier more consistent way of checking that the code is run if the character is found only.

1 Like