函数内变量赋值不生效求助:无法修改外部布尔变量值
问题原因
Python里的布尔值(True/False)属于不可变类型。当你把item1作为参数传入函数时,函数内部的iflag只是拿到了item1当前值的一个引用。当你在函数里执行iflag = False,本质是让局部变量iflag指向了一个新的False对象,完全和外部的item1切断了关联,所以外部的item1不会被修改。
解决方法
方法1:返回修改后的值,重新赋值给原变量
修改函数让它返回更新后的iflag,调用时把返回值重新赋值给item1:
test1 = "item1" item1 = True britems = [test1] inventory = [] def itemtake(item,iflag,roomit): if iflag == True: print("You take the", item) inventory.append(item) roomit.remove(item) iflag = False print(item,"=",iflag) else: print("Can't take that") return iflag # 返回修改后的值 gameIn = input("Take? ") if gameIn == "take item1": item1 = itemtake(test1,item1,britems) # 重新赋值给item1 print(test1,"=",item1)
方法2:用可变容器包装布尔值
用列表这类可变类型存放布尔值,可变类型的元素修改会直接影响外部:
test1 = "item1" item1 = [True] # 用列表包装布尔值 britems = [test1] inventory = [] def itemtake(item,iflag,roomit): if iflag[0] == True: # 访问列表内的布尔值 print("You take the", item) inventory.append(item) roomit.remove(item) iflag[0] = False # 修改列表内的元素 print(item,"=",iflag[0]) else: print("Can't take that") gameIn = input("Take? ") if gameIn == "take item1": itemtake(test1,item1,britems) print(test1,"=",item1[0]) # 打印列表内的布尔值
方法3:正确使用global关键字
如果要使用global,不要把变量作为参数传入函数,因为参数会成为局部变量覆盖全局引用。直接在函数内声明全局变量并修改:
test1 = "item1" item1 = True britems = [test1] inventory = [] def itemtake(item,roomit): # 移除iflag参数 global item1 # 声明使用全局的item1变量 if item1 == True: print("You take the", item) inventory.append(item) roomit.remove(item) item1 = False print(item,"=",item1) else: print("Can't take that") gameIn = input("Take? ") if gameIn == "take item1": itemtake(test1,britems) # 不再传递item1参数 print(test1,"=",item1)
内容的提问来源于stack exchange,提问作者burgerpants
相关产品推荐
相关产品推荐

