这可能是一个非常明显的问题,但是我刚开始使用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
很抱歉,它很长,但解释我的问题的时间越短越好。我已经多次检查缩进,然后再次缩进和缩进,所以我可以肯定不是那样,但是如果我犯了一个愚蠢的错误,那就对不起!
非常感谢您!
答案 0 :(得分:1)
将这些行更改为相同的缩进级别:
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)
答案 1 :(得分:1)
问题是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))