KnowledgeBoat Logo

Computer Science

The code provided below is intended to swap the first and last elements of a given tuple. However, there are syntax and logical errors in the code. Rewrite it after removing all errors. Underline all the corrections made.

def swap_first_last(tup)
    if len(tup) < 2:
    return tup
    new_tup = (tup[-1],) + tup[1:-1] + (tup[0])
    return new_tup

result = swap_first_last((1, 2, 3, 4))
print("Swapped tuple: " result)

Python Functions

4 Likes

Answer

def swap_first_last(tup) # Error 1
    if len(tup) < 2:
    return tup  # Error 2
    new_tup = (tup[-1],) + tup[1:-1] + (tup[0])  # Error 3
    return new_tup

result = swap_first_last((1, 2, 3, 4))
print("Swapped tuple: " result) # Error 4

Error 1 — The function header is missing a colon (:) at the end, which is required to define a function in Python.

Error 2 — The return statement needs to be indented because it is the part of the if block.

Error 3 — Comma should be added after tup[0] to ensure it is treated as a tuple. Without the comma, (tup[0]) is treated as an integer.

Error 4 — Comma should be added in the print statement to properly separate the string from the variable.

The corrected code is:

def swap_first_last(tup):  
    if len(tup) < 2:        
        return tup 
    new_tup = (tup[-1],) + tup[1:-1] + (tup[0],)
    return new_tup

result = swap_first_last((1, 2, 3, 4))
print("Swapped tuple: ", result) 

Answered By

1 Like


Related Questions