adohertyd
adohertyd

Reputation: 2689

How to read from terminal to int list in Python

I want to prompt the user to enter 2 numbers into a list of ints, add the 2 numbers and append the result to the list, and finally subtract the 2 numbers and append the result to the list. This was an assignment given to us while learning C. I'm trying to learn Python myself using the same assignments. My code won't append the results of the equations to the array. The error says list indices should be integers not tuples. Here's my code:

numarray=[]

num1 = int(raw_input("Enter the first number: "))
num2 = int(raw_input("Enter the second number: "))
num3 = num1+num2
num4 = num1-num2

print numarray[num1,num2,num3,num4]

Upvotes: 0

Views: 1576

Answers (2)

mrketchup
mrketchup

Reputation: 118

After you set all of the num* variables, you should then do this:

numarray = [num1, num2, num3, num4]

print numarray

The call numarray[num1,num2,num3,num4] is illegal because the list[] syntax is used for accessing the given index of the list, not setting items in the list.

Upvotes: 1

Scott
Scott

Reputation: 2922

You can assign the array elements like this:

numarray = [num1, num2, num3, num4]

Alternatively, you could actually append the values like you specified in the your text:

num1 = int(raw_input("Enter the first number: "))
num2 = int(raw_input("Enter the second number: "))
numarray = [num1, num2]
numarray.append(num1 + num2)
numarray.append(num1 - num2)

Then to access the elements, you use the same notation as C (e.g. numarray[0] would be the first element).

Upvotes: 2

Related Questions