Page 291 - CTS - CSA TP - Volume 2
P. 291

COMPUTER SOFTWARE APPLICATION - CITS



                 ifusername!=correct_usernameorpassword!=correct_password:

                 raiseValueError(“Incorrect username or password.”)
                 exceptValueErrorase:
                 print(f”Authentication Error: {e}”)
                 else:
                 print(“Authentication successful.”)
           Explanation:

           •  The program expects the user to input a username and password.
           •  If the entered credentials do not match the correct ones, a ValueError is raised.
           •  The except block catches this exception and prints an authentication error message.
           •  If no exception occurs, the else block executes, indicating successful authentication.

           Output:






















           Related Exercises:
           1  Write a program that tries to access an element at a specific index in a list. Handle the IndexError if the index
              is out of range.

           2  Create a program that concatenates two strings entered by the user. Handle the TypeError if the user enters
              a non-string value
           3  Write a program that asks the user to input their age. Raise a custom exception if the user enters a negative
              value.
           4  Create a dictionary and try to access a key that doesn’t exist. Handle the KeyError gracefully.
           5  Write a program that uses assert to check whether a given number is positive. Handle the AssertionError if the
              condition is not met.






















                                                           276
                              CITS : IT & ITES - Computer Software Application - Exercise 131
   286   287   288   289   290   291   292   293   294   295   296