Python
Python
def main():
# Create a bool variable to use as a flag.
found = False
# split the record into the two fields description and quantity
description, quantity = record.split(',')
quantity = int(quantity)
EXCEPTIONS
Exceptions in Python are a way to handle errors and unexpected situations in your code. When an error occurs, Python raises an exception, which is
an object that represents the error. You can catch and handle exceptions using the try-except block. Inside the try block, you write the code that might
raise an exception, and inside the except block, you define how to handle the exception. This helps to prevent your program from crashing and allows
you to gracefully handle errors. IT IS error that occurs while a program is running
EXAMPLE:
# This program divides a number by another number.
def main():
# Get two numbers.
num1 = int(input('Enter a number: '))
num2 = int(input('Enter another number: '))
# Divide num1 by num2 and display the result.
result = num1 / num2
print(num1, 'divided by', num2, 'is', result)
# Call the main function.
main()
Many exceptions can be prevented by careful coding
EXAMPLE:
# This program displays the contents
# of a file.
def main():
# Get the name of a file.
filename = input('Enter a filename: ')
try:
# Open the file.
infile = open(filename, 'r')
# Read the file's contents.
contents = infile.read()
# Display the file's contents.
print(contents)
# Close the file.
infile.close()
except FileNotFoundError:
print('An error occurred trying to read the file', filename)
print('Done')
# Call the main function.
main()