Почему этот код, который проверяет ввод данных пользователем, не работает должным образом? - PullRequest
1 голос
/ 21 января 2020

Когда я спрашиваю пользователя, какой объект он хотел бы использовать, программа игнорирует оператор elif.

from __future__ import print_function
import random

#Variables

name = raw_input
answer = raw_input
objectList = ['coin', 'piece of paper', 'bundle of sticks']

#Game code

def game():
    name = raw_input("What is your name?: ")
    print ('-----------------------------------------------------------------')
    print ('Hello, ' +  str(name) + ', you tripped into a hole and fell unconcious')
    print ('to wake up in a dungeon. There is a door in front of you, but it ')
    print ('seems to be locked.')
    print ("\n")
    print ('Look around for a tool?')
    askForObject()


#answer for question
def askForObject():
    if "yes" in answer():
        print('-----------------------------------------------------------------')
        print('There are two objects on the ground; a mysterious contraption with')
        print('two prongs, and a ' + random.choice(objectList) + '.')
        print("\n")
        print('Which tool will you pick up? The contraption or the object?')
        pickUpPrompt()               
    else:
        print('What do you mean? Yes, or no?')
        askForObject()

        #ask the user what tool they will pick up
def pickUpPrompt():
    if 'object' in answer():
        print('You picked up the object, but it has no apparent use on the door')
        print('Try again')
        pickUpPrompt()
    elif 'contraption' in answer():
            print('You picked up the contraption.')
            doorPrompt()    
    else:
        print('What object are you talking about?')
        pickUpPrompt()
def doorPrompt():
    print ('-----------------------------------------------------------------')
    print ('Will you use the contraption on the door?')
    if 'yes' in answer():
        print ('door')

game()

Вместо этого я попытался использовать другие операторы, но у меня возникли проблемы с тем, как Строка называется. Кажется, это работает, если вы вводите один и тот же ответ дважды, но я не знаю, почему это так.

1 Ответ

0 голосов
/ 21 января 2020

elif не работает должным образом, потому что он вызывает raw_input во второй раз. Вот почему ввод одного и того же ответа дважды работает, потому что вторая запись соответствует условию elif. Что вы можете сделать, это вызвать raw_input в первой строке pickUpPrompt и сохранить его как переменную, а затем использовать if / elif / else.

def pickUpPrompt():
    ans = answer()
    if 'object' in ans:
        print('You picked up the object, but it has no apparent use on the door')
        print('Try again')
        pickUpPrompt()
    elif 'contraption' in ans:
            print('You picked up the contraption.')
            doorPrompt()    
    else:
        print('What object are you talking about?')
        pickUpPrompt()
...