DevNet Associate DEVASC 200-901 Official Certification Guide by Adrian Iliesiu (z-lib.org)

(andrew) #1
print(f'Sorry, {filename} doesn't
exist! Please try again.')
else:
print(file_data)
x = 0
break
finally:
x += 1
if x == 3:
print('Wrong filename 3
times.\nCheck name and Rerun.')
break

In this example, a variable keeps track of the number of
times the while loop will be run. This is useful for
building in some logic to make sure the program doesn’t
drive the users crazy by constantly asking them to enter a
filename. Next is an infinite while loop that uses the fact
that the Boolean True will always result in continuing
looping through the code. Next is the try statement,
which contains the block of code you want to subject to
error handling. You ask the user to enter a filename to
open, and it is stored in the filename variable. This
variable is used with open() to open a read-only text file
and use the file handle object fh. The file handle object
uses read() to store the text file in the file_data
variable. If Python can’t find the file specified, the
except FileNotFoundError block of code is executed,
printing an error message with the file’s name and
informing the user to try again. The else block runs only
if an exception does not occur and the filename can be
found. The file_data is printed, x is set to 0 (to empty
the counter), the loop is stopped, and the finally block is
run. The finally block runs regardless of whether an
exception occurs each time through the loop. The x
variable is incremented each time through the loop, and
if the user gets the wrong filename three times, a
message is printed, saying the user tried three times and
to check the file. At this point, the loop is broken, and the
script is halted.

Free download pdf