0

Just started learning python with Zed Shaw's book. In one of the exercises with def function want to use raw_input and don't know how to achieve this. Any help and advice appreciated.

When running code I'm getting this error:

 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

Regards, Alex

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)
John
  • 2,633
  • 4
  • 19
  • 34
mrtwister
  • 1
  • 1
  • 1
    "Just started learning python with Zed Shaw's book" that book is very old, and it's teaching you a version of Python that is no longer supported. I _strongly_ urge you to find a resource for learning Python 3.6 or later, ideally version 3.8. – ChrisGPT was on strike Jun 20 '20 at 18:08
  • 1
    Are you sure you want to learn the outdated Python 2? – Klaus D. Jun 20 '20 at 18:08
  • Hey Chris, thanks for the reply. Any recommendations on the resources? – mrtwister Jun 20 '20 at 18:26
  • Off-site recommendations are off-topic here as defined in the [help/on-topic], but I always start [at the source](https://www.python.org/about/gettingstarted/). – ChrisGPT was on strike Jun 20 '20 at 21:06

2 Answers2

0

The problem is raw_input returns an str (i.e. a string), but the %d format type expects a number. You can convert it to a number using int():

...
boys = int(raw_input(">"))
...
girls = int(raw_input(">"))
...
oranav
  • 21
  • 2
0

Whatever input you give as user input, it is received as string by default.

In the print statement you are specifying that you would be printing an integer value (%d in print statement) but then again you are passing string value which was stored from user input.

You need to convert the raw_input into integer first.

Try this :

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 = int(raw_input(">"))
print "How many girls in the school?"
girls = int(raw_input(">"))
boys_and_girls(boys, girls)
Prashant Kumar
  • 2,057
  • 2
  • 9
  • 22