ЁЯУв Too many exams? DonтАЩt know which one suits you best? Book Your Free Expert ЁЯСЙ call Now!


    Question

    A Python function get_element(arr, index) is supposed to

    return the element at a given index. def get_element(arr, index): ┬а ┬а # Assume arr is a list of integers ┬а ┬а if index >= 0 and index ┬а ┬а ┬а ┬а return arr[index] ┬а ┬а else: ┬а ┬а ┬а ┬а return None If arr = [10, 20, 30] and get_element(arr, 3) is called, what will be the outcome, and what is the most direct fix for the logical error in the if condition to prevent an IndexError for valid indices?
    A Returns None; change index <= len(arr) to index < len(arr). Correct Answer Incorrect Answer
    B Returns None; change index <= len(arr) to index <= len(arr) - 1. Correct Answer Incorrect Answer
    C Raises IndexError; change index <= len(arr) to index < len(arr). Correct Answer Incorrect Answer
    D Raises IndexError; change index <= len(arr) to index > len(arr) - 1. Correct Answer Incorrect Answer
    E Returns 30; no bug in the condition. Correct Answer Incorrect Answer

    Solution

    тАв Dry Run: o arr = [10, 20, 30] o len(arr) is 3. o Call get_element(arr, 3): яВз index is 3. яВз The if condition 3 >= 0 and 3 яВз The code then attempts to execute return arr[3]. яВз Since arr has elements at indices 0, 1, and 2, attempting to access arr[3] (the 4th element) results in an IndexError. тАв Fix: To correctly check for valid indices, the upper bound should be strictly less than the length of the array. So, index < len(arr). тАв Why Correct Answer (C): Raises IndexError; change index o The dry run confirms that an IndexError will be raised. o The suggested fix index < len(arr) correctly ensures that index is within the valid range 0 to len(arr) - 1.

    Practice Next
    More IT Operating System Questions
    ask-question