0

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!

2
  • you want to add the numbers.. but what do you want to do with the results? Commented Sep 11, 2011 at 15:42
  • I want to print the results with the format function. Commented Sep 11, 2011 at 15:46

2 Answers 2

1

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]))
Sign up to request clarification or add additional context in comments.

Comments

1

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.

6 Comments

:Thanks a lot for the answer but i don't know yet the map function.Is there another way?Also, i want to use the "format" function.
@George: You could also use a list comprehension: [sum(t) for t in mytuple]
your printing assumes that there were two entries (pairs).
I want to input pairs.Not only 2 entries,but in order to understand how it works iuse 2.Also,i don't know yet list comprehension:)
@George: see my answer for beginner-level solution but both list comprehensions and map + filter are great tools and can create a lot more terse code. learn them ;)
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.