python – 为什么我不能打印函数内声明的变量?

python – 为什么我不能打印函数内声明的变量?,第1张

概述我正在尝试编写代码以在输入后显示英雄的属性.但它们在输出端都返回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 t 我正在尝试编写代码以在输入后显示英雄的属性.但它们在输出端都返回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 = 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 = 0hero_agi = 0hero_int = 0hero_attribute_input(hero_str,hero_int)#Why don't the variables change after this?print hero_strprint hero_agiprint 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 = 0hero_agi = 0hero_int = 0hero_str,hero_int)print hero_strprint hero_agiprint hero_int

注:这是python 2.7上的运行代码,并且成功运行时没有错误.如果你仍然面临问题,那么问题出在其他地方.

总结

以上是内存溢出为你收集整理的python – 为什么我不能打印函数内声明的变量?全部内容,希望文章能够帮你解决python – 为什么我不能打印函数内声明的变量?所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址:https://www.54852.com/langs/1193553.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-06-03
下一篇2022-06-03

发表评论

登录后才能评论

评论列表(0条)

    保存