PYTHON QUESTION


Exercise 9.2.9: Strings To Integers 6 points

Make a function called safe_int that takes a single argument. This function

should try to convert the argument into an integer. If this succeeds, the

function should return that integer. Otherwise, the function should return 0.

Then, use this function in a list comprehension to create a list out of the

given list. The new list should contain either a O or the correct integer in

place of every string in the given list:

[0, 2, 7, 0]

Make sure to print out the resulting list.

Respuesta :

Answer:

num=[]

a=input("Enter the number count")

i=0

for i in range(0,int(a)):

   b=input("Enter the number")

   num.append(b)

def safe_int(num):

   i=0

   for i in range(0,int(a)-1):

       if( num[i].isdigit()):

           num[i]=num[i]

       else:

           num[i]=0

safe_int(num)

print(num)

Explanation:

Above we have entered a list, and then pass it to the function. There we check if each item of list is an integer, and if it is an integer it is left as it is, or else 0 is stored for it in the list.