浮点输入无法识别及Python中current_location变量不更新问题求助
问题排查:current_location未更新的原因
核心问题是你没有将move_player函数返回的新位置赋值回current_location变量。
具体原因
Python中字符串属于不可变类型,当你把current_location传入函数作为location参数时,传递的是变量的值副本。函数内部计算出的new_location只是局部变量,不会自动同步到外部的current_location。必须显式接收函数的返回值,才能更新原变量。
修正方法
把原来的函数调用语句:
move_player(current_location, player_input)
改成:
current_location = move_player(current_location, player_input)
完整修正后的代码
areas = { 'geysers':{'north':'caves', 'south':'fields', 'east':'swamps', 'west':'treetops', 'item':'start'}, 'caves':{'south':'geysers', 'east':'cliffs', 'item':'sword'}, 'fields':{'north':'geysers', 'east':'temple', 'item':'bandages'}, 'swamps':{'north':'pond', 'west':'geysers', 'item':'tranquilizer'}, 'treetops':{'east':'geysers', 'item':'blowtorch'}, 'cliffs':{'west':'caves', 'item':'shield'}, 'pond':{'south':'swamps', 'item':'javelin'}, 'temple':{'west':'fields', 'item':'villain'} } current_location = 'geysers' def invalid_move(): print('Move not valid. Try again.') player_input = input('Enter your move:\n>').lower().split() def move_player(location, player_move): new_location = location if player_move[0] == 'go': if player_move[1] in areas[location] and player_move[1] != 'item': new_location = areas[location][player_move[1]] else: invalid_move() else: invalid_move() return new_location # 关键修正:将返回值赋值给current_location current_location = move_player(current_location, player_input) print(current_location)
内容的提问来源于stack exchange,提问作者Gil Savage
相关产品推荐
相关产品推荐

