Python代码给出错误 - TypeError:并非在字符串格式化期间转换所有参数

时间:2017-05-14 11:50:41

标签: python

我正在练习这个程序,要求用户提供输入并显示输出 我用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)

我收到以下错误:

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

3 个答案:

答案 0 :(得分:1)

Python尝试将所有3个变量(age,height,weight)应用于最后一个字符串:“I weigh%r”。

只使用一个字符串:

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

答案 1 :(得分:0)

您正在尝试将字符串格式设置为三个单独的字符串。更简洁的方法可能是使用format,你可以组合三个字符串(给出一个在新行上打印的例子)。此外,无需在单独的行中printraw_input

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)

答案 2 :(得分:0)

像这样重新格式化代码将为您提供预期的结果。

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 %r yrs old", "I am %r tall" , "I weigh %r” “ %(age,height,weight)被括起来为("I am %r yrs old"), ("I am %r tall") , ("I weigh %r” “ %(age,height,weight) )

因此错误。