George
George

Reputation: 5691

python add elements in a tuple

i have done the following code in order to fill a tuple with user input and then add the elements of the tuple.For example giving as input 1,2 and 3,4 i have the tuple : ((1,2),(3,4)).Then i want to add 1+2 and 3+4.

This is the first part which works ok:

data=[]
mytuple=()

while True:
    myinput=raw_input("Enter two integers: ")
    if not myinput:
        print("Finished")
        break
    else: 
        myinput.split(",")
        data.append(myinput)
        mytuple=tuple(data)
print(data)
print(mytuple)

Then , try sth like:

for adding in mytuple:
    print("{0:4d} {1:4d}".format(adding)) # i am not adding here,i just print

I have two problems: 1) I don't know how to add the elements. 2) When i add the second part of the code(the adding) ,when i press enter instead of causing the break of the program it continues to ask me "Enter two integers"

Thank you!

Upvotes: 0

Views: 9545

Answers (2)

unutbu
unutbu

Reputation: 880827

Using the built-in map function:

data=[]
mytuple=()

while True:
    myinput=raw_input("Enter two integers: ")
    if not myinput:
        print("Finished")
        break
    else: 
        myinput=map(int,myinput.split(","))                  # (1)
        data.append(myinput)
        mytuple=tuple(data)

print(data)
# [[1, 2], [3, 4]]
print(mytuple)
# ([1, 2], [3, 4])
print(' '.join('{0:4d}'.format(sum(t)) for t in mytuple))    # (2)
#    3    7
  1. Use map(int,...) to convert the strings to integers. Also note there is an error here in the orginal code. myinput.split(",") is an expression, not an assignment. To change the value of myinput you'd have to say myinput = myinput.split(...).
  2. Use map(sum,...) to apply sum to each tuple in mytuple.

Upvotes: 1

Karoly Horvath
Karoly Horvath

Reputation: 96316

You need:

myinput = myinput.split(",")

and

data.append( (int(myinput[0]), int(myinput[1])) )

and

for adding in mytuple:
    print("{0:4d}".format(adding[0] + adding[1]))

Upvotes: 1

Related Questions