0
import math  
def ListSqrRoot(nums):  
    n=len(nums)  
    for i in range(n):  
        nums[i]=math.sqrt(nums[i])  


def main():  
    nums=eval(input("Please enter a list of numbers:"))  
    print( "Before calling the function your list is:")  
    print (nums)  
    ListSqrRoot(nums)  
    print ("After calling the function your list is:")  
    print (nums)  

main()
Nir Alfasi
  • 53,191
  • 11
  • 86
  • 129

2 Answers2

0

The problem is that eval(input("Please enter a list of numbers:")) returns a tuple which is immutable and you're trying to modify it here:

nums[i] = math.sqrt(nums[i])  

It can be fixed by creating a list instead:

nums = [x for x in eval(input("Please enter a list of numbers:"))]

Warning: eval is evil!

Nir Alfasi
  • 53,191
  • 11
  • 86
  • 129
0

The core problem is that the expression you enter into eval, such as "1, 2, 3" are tuples, which are immutable, i.e., unable to be changed.

Additionally, using eval like this is dangerous, and can lead to some confusing errors. (What happens if you put in an empty list?) Python has plenty of nice string manipulation functions, so it is also completely unnecessary. Try,

line = input('enter numbers:')
nums = [int(s.strip()) for s in line.strip().split(',') if s]
tahsmith
  • 1,643
  • 1
  • 17
  • 23