Computer Science, asked by allenat680022, 8 months ago

write a python program using functions to read a list and replace all even numbers with 2 ​

Answers

Answered by Retik7
1

Explanation:

If you want to input the list in function itself:

def func():

ls = [int(n) for n in input("Enter numbers").split()]

for it in range(len(ls)):

if ls[it]%2==0:

ls[it]=2

print(ls)

#Calling Function

func()

#Input

Enter numbers 1 2 3 4 5 6 7 8

#Output

[1, 2, 3, 2, 5, 2, 7, 2]

By Passing List in a function parameter:

def func(ls):

for it in range(len(ls)):

if ls[it]%2==0:

ls[it]=2

print(ls)

#Calling Function

func([1,2,3,4,5,6,7,8])

#Output

[1, 2, 3, 2, 5, 2, 7, 2]

Answered by Equestriadash
3

data = eval(input("Enter the data: "))

print("The original list is: ", data)

for i in range(len(data)):

 if data[i]%2 == 0:

     data[i] = 2    

print("The new list is: ", data)

  • eval() is for accepting data, as they're entered.
  • We use len(variable_name) since the user can enter up to n values.
  • We then check if that value is divisible by two.
  • If it satisfies the condition above, 2 is the value assigned to its index position.
  • The new list is then displayed.

Attachments:
Similar questions