簡體   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