Richa
Richa

Reputation: 161

Python code giving an error - TypeError: not all arguments converted during string formatti

I was practicing this program which asks the user to give their inputs and displays output.
I'm running the program with IDLE.

print "How old are you"
age= raw_input()
print "How tall are you"
height=raw_input()
print "How much do you weigh?"
weight=raw_input()

print "I am %r yrs old", "I am %r tall" , "I weigh %r” “ %(age,height,weight)

I am getting the following error:

How old are you
34
How tall are you
34
How much do you weigh?
34
I am %r yrs old I am %r tall

Traceback (most recent call last):
  File "/Users/r/Documents/new.py", line 8, in <module>
    print "I am %r yrs old", "I am %r tall" , "I weigh %r" %(age,height,weight)

TypeError: not all arguments converted during string formatting

Upvotes: 0

Views: 35

Answers (3)

srj
srj

Reputation: 10111

Reformatting your code like this will give you the expected results.

print "How old are you"
age= raw_input()
print "How tall are you"
height=raw_input()
print "How much do you weigh?"
weight=raw_input()
print ("I am %r yrs old" + " I am %r tall" + " I weigh %r” ) %(age,height,weight)

The % operator works as a binary operator between the string and the tuple provided, and its precedence is greater than the , operator. This means that it will be applied on the last string only, and then the , operator is applied.

Your expression "I am %r yrs old", "I am %r tall" , "I weigh %r” “ %(age,height,weight) gets bracketed as ("I am %r yrs old"), ("I am %r tall") , ("I weigh %r” “ %(age,height,weight) )

hence the error.

Upvotes: 0

roganjosh
roganjosh

Reputation: 13175

You're trying to use string formatting for three separate strings. A cleaner way to do this is probably to use format and you can combine the three strings (one example given to print on new lines). Also, there is no need to have print and raw_input on separate lines.

age = raw_input("How old are you\n")
height = raw_input("How tall are you\n")
weight = raw_input("How much do you weigh?\n")

print "I am {} yrs old \nI am {} tall\nI weigh {}".format(age, height, weight)

Upvotes: 0

Maurice Meyer
Maurice Meyer

Reputation: 18106

Python tries, to apply all 3 variables (age,height,weight) to the last string: "I weigh %r".

Use just one string:

print "I am %r yrs old, I am %r tall, I weigh %r" % (age,height,weight)

Upvotes: 1

Related Questions