188k views
5 votes
Write a function square_evens(values) that takes a list of integers called values, and that modifies the list so that all of its even elements are replaced with their squares, but all of its odd elements are left unchanged.

1 Answer

5 votes

Answer:

#create the function

def square_evens(values):

count_Value = 0

#loop loop for iteration

for i in values:

#check for even number

if (i) % 2 == 0:

values[count_Value] = i * i #store the square in the same index

count_Value =count_Value + 1

print(values) #print the list

# list of integers

values = [1, 2, 3, 4, 5, 6]

#calling the function

square_evens(values)

Step-by-step explanation:

The above code is written in python. first, create the function square_evens() which takes one parameter of the list.

inside the function declare the variable and then take a for loop for traversing each element in the list. Inside the for loop, we take the if-else statement for checking the number is even. if the number is even then stored the square of that value in the same list. To store the square value in the same index, we take the count variable for tracking the index.

After the all element in the list checked, the program terminates the loop and then print the updated list on the screen.

Outside the function, create the list with an integer value and then calling the function with passing the list argument.

NOTE: In the python programming, please keep the indentation in code.

User Zuzanna
by
8.2k points