Python字典和函数

2024-09-24 12:23:10 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要这个代码的帮助。问题是,当我运行它时,它以def hellokitchen开始,我尝试将hellokitchen()从dictionary中的“kitchen”更改为hellokitchen(),但在0xblahblahblah处打印函数hellokitchen。我需要这个来工作。 我试过另一种方法,但没有

MAP = {'foyer_forward': 'hall',
   'foyer_right': 'bedroom',
   'foyer_back': 'front door',
   'foyer_left': 'office',
   'hall_back': 'foyer',
   'hall_left':'kitchen',
   'bedroom 2_back': 'hall',
   'bedroom_back': 'foyer',
   'bedroom_left': 'bathroom',
   'front door_back': 'foyer',
   'office_back': 'foyer',
   'kitchen_back': 'hall',
   'bathroom_back': 'bedroom'}

def hellokitchen():
guess = input("your plan works!")
if guess == 'sup':
    print("YOUR PLAN DEFINITELY WORKS")
return




DESC = {'foyer': 'You are in the foyer of the house',
    'hall': 'You are in the Hall. The place is completely ruined, and you despise the look of it. ',
    'bedroom': 'You are in the bedroom. The body of the victim is lying on the floor, drenched in blood. A pungent smell is radiating out of the corpse. There are two doors, one back to the foyer, and one leading to the bathroom on the left.',
    'front door': 'The front door is locked. You have to find the murderer to escape! Type back to return to the foyer.',
    'office': 'You walk into a room which looks like an Office. You scour the room for evidence but return nothing. Type back to return to the foyer.',
    'kitchen': hellokitchen(),
    'bathroom': 'You are in the bathroom'}


FINISH = 'SECRET_ROOM'
UNLOCKED_DOOR = 'kitchen'

name = input('\033[1;36;1m What is your name? > ')
print('Hello', name)
print("ENTER STARTING DESC.")

room = 'foyer'

while True:
print(DESC[room])
if room in FINISH:
    break

direction = input('Enter a direction. Choose from forward, back, left, right or quit >')
key = room + '_' + direction

if key in MAP:
    room = MAP[key]

else:
    print('You can\'t go ' + direction + '.')

print('Congratulations!')

Tags: thetoinyoubackleftareroom
1条回答
网友
1楼 · 发布于 2024-09-24 12:23:10

问题出在

print(DESC[room])

当你在厨房的时候,你会有这样的感觉:

print(hellokitchen)

它打印出内存行,正如您前面所描述的,因为它告诉python打印出名为hellokitchen的函数对象,函数对象的表示形式类似于您上面所描述的,类似于:

<function hellokitchen at 0x0000000004351C18>

您的意图是,python调用名为hellokitchen的函数,您可以通过将print(DESC[room])更改为:

if callable(DESC[room]):    # you have a function in your dict
    DESC[room]()            # call that function
else:
    print(DESC[room])       # in case of string, just print it

这将检查您是否在字典中保存了函数(比如for 'kitchen': hellokitchen),或者没有(您有一个可以直接打印的字符串,比如'bathroom': 'You are in the bathroom'

相关问题 更多 >