Performing mathematical operations on list entries

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Phox
    New Member
    • Apr 2008
    • 4

    Performing mathematical operations on list entries

    I'm learning Python, and as a small exercise I made for myself I'm writing a program to find the determinate of a 2x2 matrix. I'm running Python 2.5 on Windows Vista, here's my code.

    Code:
    #for loop test.
    #Finding the determinate of a 2x2 matrix
    
    matrix = []
    
    newelement = raw_input("Enter your first value: ")
    matrix.append(newelement)
    
    while len(matrix) < 4:
    	nextelement = raw_input("enter your next element: ")
    	matrix.append(nextelement)
    
    int(matrix[0])
    int(matrix[1])
    int(matrix[2])
    int(matrix[3])
    determinate = (matrix[0]*matrix[3])-(matrix[1]*matrix[2])
    print "The determinate of your matrix is "+ determinate +"."
    The error I get tells me that the elements of matrix are strings and thus the * operation cannot be performed on them.

    I'm a bit embarrassed to ask such a simple question, but I really know very little about Python and I've done as much research as I can given the resources I have (how I found int() which doesn't seem to work). Advice?
  • bvdet
    Recognized Expert Specialist
    • Oct 2006
    • 2851

    #2
    Originally posted by Phox
    I'm learning Python, and as a small exercise I made for myself I'm writing a program to find the determinate of a 2x2 matrix. I'm running Python 2.5 on Windows Vista, here's my code.

    Code:
    #for loop test.
    #Finding the determinate of a 2x2 matrix
    
    matrix = []
    
    newelement = raw_input("Enter your first value: ")
    matrix.append(newelement)
    
    while len(matrix) < 4:
    	nextelement = raw_input("enter your next element: ")
    	matrix.append(nextelement)
    
    determinate = (int(matrix[0])*int(matrix[3]))-(int(matrix[1])*int(matrix[2]))
    print "The determinate of your matrix is "+ determinate +"."
    The error I get tells me that the elements of matrix are strings and thus the * operation cannot be performed on them.

    I'm a bit embarrassed to ask such a simple question, but I really know very little about Python and I've done as much research as I can given the resources I have (how I found int() which doesn't seem to work). Advice?
    You were very close. You can modify the contents of a list, but you have to assign the modified value to the list element. Example:[code=Python]matrix[0]=int(matrix[0])[/code]I modified your code in the quoted post above, which is another option. Yet another way:[code=Python]
    newelement = int(raw_input(" Enter your first value: "))[/code]HTH :)

    Comment

    Working...