Madlibs issue


$ python
Mad Libs is starting
Enter a name: g
Enter an adjective: j
Enter a second adjective: j
Enter one more adjective: h
Enter a verb: df
Enter a second verb:
Enter one more verb: dd
Enter a noun: s
Enter a second noun: w
Enter a third noun: e
Enter one more noun: r
Enter an animal: f
Enter a food: f
Enter a fruit: f
Enter a number: s
Enter a superhero: w
Enter a country: w
Enter a dessert: w
Enter a year: e
Traceback (most recent call last):
File "", line 39, in
print STORY % (first_adj,name,first_verb,secon
TypeError: %d format: a number is required, not str

Im getting this error, how should I fix it?


Hi @newbiewcoder ,

Without our seeing more of your code, we cannot be sure of the problem. But, judging from what you have posted, it appears likely that it relates to your having entered s in response to the prompt ...

Enter a number

You have ...

Enter a number: s

Whether this is, in fact, the source of the error depends upon how your code handles the value that is entered in response to that prompt.

In the Mad Libs story, the number that is entered specifies how many rats were encountered at the sewers. Here's a little piece of my code ...

into the sewers and found %s rats.

Notice the %s format specifier that handles the number. This will accept an int, but also allows the value to be a string.

If your code has the following ...

into the sewers and found %d rats.

... the %d format specifier requires a corresponding int as an output value. If, instead of an int, you entered a string, you will get an error. You could use %s instead of %d. In that case, if someone enters a string, such as nine, the program will be able to handle it without raising an error.

Keep in mind that the raw_input function returns a str, even if you enter a digit in response to the prompt. While a str is appropriate for the program, you would need to convert the response into a number if you needed it for some mathematical work. In that case, you could do this ...

number = int(raw_input("Enter an integer: "))

... or ...

number = float(raw_input("Enter a floating point number: "))