python – 为什么我不能打印函数内声明的变量?
发布时间:2020-12-20 11:47:06 所属栏目:Python 来源:网络整理
导读:我正在尝试编写代码以在输入后显示英雄的属性.但它们在输出端都返回0 #This is one of code block that i use to calculate damage of heroes in Dota 2def hero_attribute_input(hero_str,hero_agi,hero_int): print "Input the str of the hero" hero_str
我正在尝试编写代码以在输入后显示英雄的属性.但它们在输出端都返回0
#This is one of code block that i use to calculate damage of heroes in Dota 2 def hero_attribute_input(hero_str,hero_agi,hero_int): print "Input the str of the hero" hero_str = int(raw_input("> ")) print "Input the agi of the hero" hero_agi = int(raw_input("> ")) print "Input the int of the hero" hero_int = int(raw_input("> ")) # Why can't you add a print commat here? return (hero_str,hero_int) hero_str = 0 hero_agi = 0 hero_int = 0 hero_attribute_input(hero_str,hero_int) #Why don't the variables change after this? print hero_str print hero_agi print hero_int 解决方法
虽然你可以把它变成全球性的,但这不是一个好习惯.而是这样做:
hero_str,hero_int = hero_attribute_input(hero_str,hero_int) 要解释这一点,您要更新变量,但这不会影响函数范围之外的变量. 因此,您需要使用您从函数返回的更新值重新分配变量. return (hero_str,hero_int) 因此,完整代码应该或多或少如下: def hero_attribute_input(hero_str,hero_int): print "Input the str of the hero" hero_str = int(raw_input("> ")) print "Input the agi of the hero" hero_agi = int(raw_input("> ")) print "Input the int of the hero" hero_int = int(raw_input("> ")) return (hero_str,hero_int) hero_str = 0 hero_agi = 0 hero_int = 0 hero_str,hero_int) print hero_str print hero_agi print hero_int 注:这是python 2.7上的运行代码,并且成功运行时没有错误.如果你仍然面临问题,那么问题出在其他地方. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |