Python Programme on EXPECTION HANDLING
Python Programme on EXPECTION HANDLING
1.Define Your Function: Begin by creating a function that performs the main task.
For example, if you're calculating the total, count, and average of numbers entered
by a user, define a function named calculate_statistics.
2.Use TRY Block: Inside your function, use a try block to wrap the code that might
cause an error. This code can include reading user inputs and performing
calculations, such as adding numbers to a total.
3.Handle Specific Exceptions: Within the try block, handle specific exceptions that
may arise from user inputs. For example, catching ValueError when converting input
to an integer can help manage non-numeric entries.
4.Provide an EXCEPT Block: After the try block, add an except block that will
execute if an exception occurs. This block can print an error message to inform the
user about what went wrong.
5.Complete Your Main Logic: After handling exceptions, provide logic for
calculating the total and average, and print out results when the user enters
"done". You can also count total entries successfully processed by incrementing a
counter.
def calculate_statistics():
total = 0
count = 0
while True:
user_input = input("Enter a number or 'done' to finish: ")
if user_input.lower() == 'done':
break
try:
number = float(user_input) # Convert input to a float
total += number
count += 1
except ValueError:
print("Error: Please enter a valid number.") # Handle non-numeric
input.
if count > 0:
average = total / count
print(f'Total: {total}, Count: {count}, Average: {average}')
else:
print('No valid numbers were entered.')
OUTPUT:
SUMMARY:
This code allows users to input numbers repeatedly. When "done" is entered, it
provides the total, count, and average. If anything other than a number is entered,
it catches the ValueError and prompts the user to correct the input.