首页 > 解决方案 > 艰难地学习 Python:练习 19

问题描述

刚开始用 Zed Shaw 的书学习 python。在其中一个def function想要使用raw_input但不知道如何实现的练习中。任何帮助和建议表示赞赏。

运行代码时出现此错误:

 File "drills19.py", line 27, in <module>
    boys_and_girls(boys, girls)
  File "drills19.py", line 2, in boys_and_girls
    print "In your school there are %d boys." % boys_count
TypeError: %d format: a number is required, not str

问候,亚历克斯

def boys_and_girls(boys_count, girls_count):
    print "In your school there are %d boys." % boys_count
    print "In your school there are %d girs." % girls_count
    print "Total number of students in the school is %d." % (boys_count + girls_count)
    print "That's a lot of students!\n"
print "How many boys on the school?"
boys = raw_input(">")
print "How many girls in the school?"
girls = raw_input(">")
boys_and_girls(boys, girls)

标签: python

解决方案


问题是raw_input返回一个str(即字符串),但%d格式类型需要一个数字。您可以使用以下方法将其转换为数字int()

...
boys = int(raw_input(">"))
...
girls = int(raw_input(">"))
...

推荐阅读