2016-07-28 3 views
1

Этот код предназначен для упражнений MadLibs от Code Academy, который должен брать несколько входов от пользователя, а затем печатать очень забавный вывод.Python - CodeAcademy Madlibs Упражнение

Существует история, уже представленная на сайте, и я ее не модифицировал.

Когда я запускаю сценарий, я получаю следующее сообщение об ошибке:

............................. ..............................................

Traceback (самый последний вызов л аст):
Файл «Madlibs.py», строка 30, в
печати «Этим утром я проснулся и почувствовал,% s, потому что _ собирается окончательно% s над большой _% s. С другой стороны% s было много% ss, протестующих против% s в магазинах. Толпа начала _ к rythym% s, что сделало все% ss очень _. % s попытался _ в канализацию и нашел% s крыс. Необходимая справка,% s быстро называется% s. % s появился и сэкономил% s, пролетев до% s и сбросив _ в лужу% s. % s затем заснул и проснулся в году _, в мире, где% ss управляли миром ».% (a1, name, v1, a2, n1, n2, Animal, Food, v2, n3, Fruit, a3, имя, v3, номер, имя, супергерой, супергерой, имя, страна, имя, десерт, название, год, n4)

TypeError: не все аргументы преобразуются во строки форматирования
......... .................................................. ................

выход также печатает «печать» !!!

Пожалуйста, обратите внимание, что в этой истории, есть некоторые места, где у нас есть " % ss 'вместо'% s '. Codeacademy хочет, чтобы пользователи использовали'% ss '(я так считаю)

Кроме того, я попытался заменить «% ss» на «% s» - я получил ту же ошибку.

Заменил все «% s» и «% ss» на «% r» и «% rr» и получил ту же ошибку.

Заменен «% rr» на «% r» повсюду и получил ту же ошибку.

Еще одна вещь, которую я должен упомянуть, код запрашивает у пользователя все исходные данные, но не заменяет их в истории и печатает историю только с% s или% r вместе с сообщением об ошибке.

Может кто-то любезно помочь мне здесь. Мой код кажется мне хорошим, и я не понимаю, что происходит с сообщением об ошибке.

Ниже приводится код (Пожалуйста, медведь со мной для этой повторяющейся части)

# This is a story for Mad Libs !!! 

print "Mad Lib is staritng now." 

name = raw_input ("What's your name ?") 

a1 = raw_input ("How are you feeling today ?") 
a2 = raw_input ("How is ther weather?") 
a3 = raw_input("Would you like your coffee hot or cold?") 

v1 = raw_input ("Would you rather jump, run or walk ?") 
v2 = raw_input ("Would you rather sing, dance or act ?") 
v3 = raw_input ("Would you rather eat, sleep or watch ?") 

n1 = raw_input ("In which city do you live ?") 
n2 = raw_input ("What is your favourite pet ?") 
n3 = raw_input ("Would you like to go to a mountain or a beach ?") 
n4 = raw_input ("DO you wnat to buy a dress or a shoe? ") 

Animal = raw_input ("Which animal do you like the most ?") 
Food = raw_input ("Enter your favourite food") 
Fruit = raw_input ("What's your favourite fruit ?") 
Number = raw_input ("Tell me a number: ") 
Superhero = raw_input ("Tell me the name of one Superhero") 
Country = raw_input ("Which country would you like to visit on your next vacation ?") 
Dessert = raw_input ("Which is your favourite dessert ?") 
Year = raw_input ("Which year were you born ?") 


print "This morning I woke up and felt %s because _ was going to finally %s over the big _ %s. On the other side of the %s were many %ss protesting to keep %s in stores. The crowd began to _ to the rythym of the %s, which made all of the %ss very _. %s tried to _ into the sewers and found %s rats. Needing help, %s quickly called %s. %s appeared and saved %s by flying to %s and dropping _ into a puddle of %s. %s then fell asleep and woke up in the year _, in a world where %ss ruled the world." %(a1, name, v1, a2, n1, n2, Animal, Food, v2, n3, Fruit, a3, name, v3, Number, name, Superhero, Superhero, name, Country, name, Dessert, name, Year, n4) 

ответ

0

Этот link предлагает решение проблемы. Прочитайте снизу. Кажется, что вам нужно заменить все _ на% s.

Так, например, вместо

print "This morning I woke up and felt %s because _ was going to finally %s over the big _ %s. On the other side of the %s were many %ss protesting to keep %s in stores. The crowd began to _ to the rythym of the %s, which made all of the %ss very _. %s tried to _ into the sewers and found %s rats. Needing help, %s quickly called %s. %s appeared and saved %s by flying to %s and dropping _ into a puddle of %s. %s then fell asleep and woke up in the year _, in a world where %ss ruled the world." %(a1, name, v1, a2, n1, n2, Animal, Food, v2, n3, Fruit, a3, name, v3, Number, name, Superhero, Superhero, name, Country, name, Dessert, name, Year, n4) 

Это должно быть

print "This morning I woke up and felt %s because %s was going to finally %s over the big %s %s. On the other side of the %s were many %s protesting to keep %s in stores. The crowd began to %s to the rythym of the %s, which made all of the %s very %s. %s tried to %s into the sewers and found %s rats. Needing help, %s quickly called %s. %s appeared and saved %s by flying to %s and dropping %s into a puddle of %s. %s then fell asleep and woke up in the year %s, in a world where %s ruled the world." %(a1, name, v1, a2, n1, n2, Animal, Food, v2, n3, Fruit, a3, name, v3, Number, name, Superhero, Superhero, name, Country, name, Dessert, name, Year, n4) 
+0

Спасибо !!!! Это решило проблему :) – Sarat

0

У вас есть много больше аргументов в вашем наборе ((a1, имя ......) аргумент), чем вы % s в вашей строке. Убедитесь, что каждый аргумент соответствует точно 1% s для форматирования строк для работы.

+0

я насчитал как число аргументов и% s и «мысль», они совпадают. Однако я заменил все «_» в моем коде на «% s», как было предложено выше, и это сработало. Спасибо :) – Sarat

Смежные вопросы