Ошибка «неверный синтаксис» при попытке запустить elif - PullRequest
0 голосов
/ 18 апреля 2020

Это может быть действительно очевидный вопрос, но я только начинаю с Python и получил синтаксическую ошибку относительно второго оператора elif в этом коде:

    if userInput == 'sleep':
        print('Goodnight... zzzzz')
        day += 1
        time = 'day'
        print('Goodmorning!')
    elif userInput == 'eat':
        if 'bread' in inventory:
            print('You have eaten 1x bread from your inventory. This has'
            ' restored your hunger by 5, and your health by 5. Your'
            ' hunger is now {}, and your health is {}.'.format(playerHunger + 5, playerHealth + 5)
    elif userInput == 'pick up':
        pickUpInput = input('What would you like to pick up?')
    if room == 1:
        if pickUpInput in r1Contents:
            print('1x {} added to inventory.'.format(pickUpInput))
            r1Contents.remove(pickUpInput)
            inventory.append(pickUpInput)

Ошибка

  File "foo.py", line 11
    elif userInput == 'pick up':
       ^
SyntaxError: invalid syntax

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

Спасибо тебя так много!

Ответы [ 2 ]

1 голос
/ 19 апреля 2020

Проблема в том, что для печати в строке над elif отсутствует закрывающая скобка. Измените его на

print('You have eaten 1x bread from your inventory. This has'
        ' restored your hunger by 5, and your health by 5. Your'
        ' hunger is now {}, and your health is {}.'.format(playerHunger =+ 5, playerHealth =+ 5))

Подобные вещи легче заметить, если вы попытаетесь не допустить, чтобы ваш код отклонялся с правой стороны

print('You have eaten 1x bread from your inventory. This has'
        ' restored your hunger by 5, and your health by 5. Your'
        ' hunger is now {}, and your health is {}.'.format(
    playerHunger =+ 5, playerHealth =+ 5))

или если вы поместите строку в отдельной переменной

msg = ('You have eaten 1x bread from your inventory. This has'
       ' restored your hunger by 5, and your health by 5. Your'
       ' hunger is now {}, and your health is {}.')
print(msg.format(playerHunger =+ 5, playerHealth =+ 5))
1 голос
/ 19 апреля 2020

Измените эти строки на тот же уровень отступа:

    elif userInput == 'pick up':
        pickUpInput = input('What would you like to pick up?')
        if room == 1:
            if pickUpInput in r1Contents:
                print('1x {} added to inventory.'.format(pickUpInput))
                r1Contents.remove(pickUpInput)
                inventory.append(pickUpInput)

Кроме того, не используйте здесь приращения (+=), поскольку они будут возвращать None, но не значение. Сначала увеличьте значения и используйте их как переменные. Код приращения неверен, измените =+ на +=.

playerHunger += 5
playerHealth += 5
...
' hunger is now {}, and your health is {}.'.format(playerHunger, playerHealth)
...