Reputation: 87
I have a function which works out whether or not the file is in a n x n square matrix i.e. 3x3 or 4x4. Now if I call the function it works fine; it says whether or not it is a nxn square.
My problem is I want to use an exception, if the function returns a False value, then it wont load the text file but give a error saying to ensure the file has a nxn grid. So for example if I have the grid stored in a text file and I try to load it with python code; the program should keep looping until the file is in the correct format. I wasn't sure if there was an exception for a function boolean
ABC
DEF
GHI
J
Currently I have
def grid(n):
rows = len(n)
for row in n:
if len(row) != rows:
return False
Similar to how the file open works; if it doesn't exist (FileNotFoundError) then it'll keep looping until it finds the input file name
Upvotes: 2
Views: 7021
Reputation: 23171
You're confusing handing the exception (the "except" statement) with raising one. What you should do in square is raise an exception instead of returning false and then handle it in your main program:
def square(sq):
rows = len(sq)
for row in sq:
if len(row) != rows:
raise ValueError("the format is incorrect")
def loaddata():
while True:
try:
filename=input("Enter the name of the file to open: ") + ".txt"
with open(filename,"r") as f:
for line in f:
splitLine=line.split()
d.append(splitLine)
break
square(d)
except FileNotFoundError:
print("File name does not exist; please try again")
except ValueError:
print("The format is incorrect")
for line in d:
print("".join(line))
return
Upvotes: 1
Reputation: 55469
Here's one way to do it. Simply raise an appropriate exception if square(d)
returns False
.
#Return True if sq is square, False otherwise
def square(sq):
rows = len(sq)
return all(len(row) == rows for row in sq)
def loaddata():
while True:
try:
filename = input("Enter the name of the file to open: ") + ".txt"
with open(filename, "r") as f:
d = []
for line in f:
splitLine = line.split()
d.append(splitLine)
if not square(d):
raise ValueError
break
except FileNotFoundError:
print("File name does not exist; please try again")
except ValueError:
print("The format is incorrect")
for line in d:
print("".join(line))
We reset d
to []
each time through the loop in case we need to get rid of the contents of a previous file that isn't square.
Upvotes: 2