2014-10-23 3 views
-2

Просто для удовольствия я хотел создать MADLIB для python. Код ниже:raw_input while loop не работает

print "WELCOME TO MADLIBS! PY V1.2.1" 
print "" 
print "To see the story type all thirteen parts of speech below" 
print "" 
print "1. Foreign Country" 
print "2. Adverb" 
print "3. Adjective" 
print "4. Animal" 
print "5. Verb (ing)" 
print "6. Verb" 
print "7. Verb (ing)" 
print "8. Adverb" 
print "9. Adjective" 
print "10. A Place" 
print "11. Type of Liquid" 
print "12. Part of the Body" 
print "13. Verb" 
print "" 

while 13: 
num=raw_input("Enter: ") 

Я хочу цикл переменных num 13 раз и как-то захватить первый по тринадцатому входы и печатать их следующим образом:

print "If you are traveling in" num "and find yourself having to cross a piranha-filled river, here's how to do it" num ". Piranhas are more" num "during the day, so cross the river at night. Avoid areas with netted" num "traps - piranhas may be" num "there looking to" num "them! When" num "the river, swim" num ". You don't want to wake them up and make them" num "! Whatever you do, if you have an open wound, try to find another way to get back to the" num ". Piranhas are attracted to fresh" num "and will most likely take a bite out of your" num "if you" num "in the water!" 

Если у вас есть лучшее решение, или фиксированное моя версия, которую я хотел бы услышать.

+0

1. Вы хотите 'for' петлю. 2. Вы переназначаете 'num' каждый раз, поэтому можете только получать доступ к последнему входу; вместо этого вы должны использовать 'list'. 3. Это не то, как вы обрабатываете строки, по крайней мере, вам нужны запятые, и вы должны действительно использовать форматирование строк. См. Https://docs.python.org/2/tutorial/index.html – jonrsharpe

+0

Решение, вероятно, поможет вам меньше, чем больше узнать о Python. В зависимости от того, насколько вы уже знаете о программировании, вам нравятся ресурсы Instant Python, Snake Wrangling for Kids, официальный учебник ... – EOL

+0

Я знаю, что это немного сложно понять, и что лучше для того, чтобы научиться, чем на самом деле закодировать. Иногда вам приходится замарать руки грязным кодированием, быть смущенным, а затем чувствовать себя как baus, когда вы что-то делаете! –

ответ

0

Попробуйте эту версию:

input_types = ['Foreign Country', 'Adverb', 'Adjective', 'Animal', 'Verb (ing)'] 
input_types.append('Verb') 
input_types.append('Verb (ing)') 
input_types.append('Adverb') 
input_types.append('Adjective') 
input_types.append('A Place') 
input_types.append('Type of Liquid') 
input_types.append('Part of the Body') 
input_types.append('Verb') 

story = '''If you are traveling in {} and find yourself having to cross 
a piranha-filled river, here's how to do it {}. 
Piranhas are more {} during the day, so cross the river at night. 
Avoid areas with netted {} traps - piranhas may be {} there looking to {} them! 
When {} the river, swim {}. You don't want to wake them up and make them {}! 
Whatever you do, if you have an open wound, 
try to find another way to get back to the {}. 
Piranhas are attracted to fresh {} and will most likely take a bite out 
of your {} if you {} in the water!''' 

print('WELCOME TO MADLIBS! PY V1.2.1\n') 
print('To see the story type all thirteen parts of speech below') 

results = [] 

for number, value in enumerate(input_types): 
    user_input = raw_input('#{} - {}: '.format(number+1, value)) 
    results.append(user_input) 

print('Here is your story: ') 
print(story.format(*results)) 
+0

Блестящий! Чисто потрясающий! Спасибо огромное! –

0

Есть две вещи, которые вы должны использовать, массивы и строка форматирования. Это сделает ваш код более понятным и понятным, за исключением того, что он сделает его более питоническим. Решение для вашего сценария будет что-то вроде этого:

print "WELCOME TO MADLIBS! PY V1.2.1" 
print "" 
print "To see the story type all thirteen parts of speech below" 
print "" 
print "1. Foreign Country" 
print "2. Adverb" 
print "3. Adjective" 
print "4. Animal" 
print "5. Verb (ing)" 
print "6. Verb" 
print "7. Verb (ing)" 
print "8. Adverb" 
print "9. Adjective" 
print "10. A Place" 
print "11. Type of Liquid" 
print "12. Part of the Body" 
print "13. Verb" 
print "" 

num = 0 
answers = [] 

while num < 13: 
    val = raw_input("Enter %s: " num + 1) 
    answers.append(val) 
    num += 1 

answer = """If you are traveling in %s and find yourself having to cross 
a piranha-filled river, here's how to do it %s. 
Piranhas are more %s during the day, so cross the river at night. 
Avoid areas with netted %s traps - piranhas may be %s there looking to %s them! 
When %s the river, swim %s. You don't want to wake them up and make them %s! 
Whatever you do, if you have an open wound, 
try to find another way to get back to the %s. 
Piranhas are attracted to fresh %s and will most likely take a bite out 
of your %s if you %s in the water!""" % (answers[0], answers[1], answers[2], 
    answers[3], answers[4], answers[5], answers[6], answers[7], answers[8], 
    answers[9], answers[10], answers[11], answers[12]) 

print answer 

Сохраняет значение в массиве, что позволяет иметь более одного значения внутри него, а затем отформатировать его в длинной строке, которая позволяет увидеть ваш результат лучше.

+0

Если вы используете 'str.format' вместо'% ', вы можете просто использовать' '...". Format (* answers) '. – jonrsharpe

+0

Ну, массив имеет смысл, но по какой-то причине он говорит, что что-то не так с ** num ** под номером num <13: –

+0

@jonrsharpe Я не знал, что вы можете отформатировать целый список. Спасибо за совет! –