繁体   English   中英

为 python 变量分配新值

[英]Assigning a new value to a python variable

我对 Python 非常陌生,并且正在开发我的第一个基于文本的游戏。 在这个游戏中,我希望玩家从角色列表中进行选择。 在游戏过程中,我也想赋予玩家改变角色的能力(这最终会影响游戏的结果)。 我无法理解我需要做些什么来确保正确保存新的角色选择。 以下是代码的精简版本:

def identity_choice():
    identity = input("""Your options are:
    1.  Ordinary Tourist
    2.  Chef
    Please choose a number""")
    if identity == "1":
        print("You now look like a tourist!")
        return identity
    elif identity == "2":
        print("You are now a chef")
        return identity
    else:
        print("Sorry, I don't understand that.")
        return identity_choice()

def action(identity):
    if identity == "1":
        print("You can't do what you need to as a tourist")
        response = input("Would you like to change your disguise?")
        if "y" in response:
            identity_choice()
        else:
            print("You have chosen to retain your identity")

identity = identity_choice()

action(identity)

变量“identity”仅用于函数的局部。 如果您需要全局变量,只需在所有函数之外声明该变量,并在函数内部输入“全局标识”行。

我不太明白你的意思。 我假设问题出在“操作(身份)”function 中,如果用户选择“y”,则不会保存新身份。 将其更改为:

def action(identity):
   if identity == "1":
      print("You can't do what you need to as a tourist")
      response = input("Would you like to change your disguise?")
   if "y" in response:
      return identity_choice()
   else:
      print("You have chosen to retain your identity")
      return identity

然后,当您调用操作时,请执行以下操作:

identity = action(identity)

简短的回答

您需要做的就是重新分配identity变量,如果这是您选择跟踪玩家身份的方式。 例如:

if "y" in response: identity = identity_choice()

在此之后,您可以根据需要return identity ,或者您可以按照其他答案的建议,在action function 描述中声明global identity 这样, identity变量在整个脚本中共享。

更长的答案

实际上不会那么长,但这似乎是学习一些面向 object 编程的好地方。 你说你才刚刚开始,所以如果太早了,那就不要打扰,你会到达那里的!

However, a nice way to set this up could be to instantiate users as an object of some class, such as user , and then this class could either have a second class identity which inherits from the user class. 或者, user class 可以简单地拥有一个名为identity的变量,可以使用简单的 function 来更改它。 这是一个非常简短且不完整的示例:

class user:
    def __init__(self):
        pass   # here you could call the choose identity function, or just 
               # initialize with some default identity
    def choose_identity():
        #the function you wrote above asking the user to choose their identity

希望这会有所帮助,我尽量保持简单

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM