如何将多个变量从一个函数移到全局范围? [英] How to move multiple variables from a function into the global scope?

查看:51
本文介绍了如何将多个变量从一个函数移到全局范围?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是python的新手,我正在创建游戏之类的垄断产品,并且正在程序的设置方面工作,并且我有一个函数可以询问用户我要为每个设置输入什么内容然后使用另一个功能将这些设置导入到文本文件中,以便可以将其存储以供以后使用,也可以让程序将其用作设置.这是我遇到的问题所在,我预计会设置大约15个左右的问题,这是我考虑将其带出另一个函数所用的唯一方法,并将其导入到全局范围中,以便可以使用在程序中,是使用return还是有另一种方式,或者我只需要对每个变量使用return

I'm new to python and I'm working on creating a monopoly like game and am working on the settings aspect of the program and I have a function that asks the user what they want to put in for each setting I am then using another function to import those settings to a text file so they can be stored for later use and also have them be used by the program as settings. Here is where my problem comes I anticipate to have around 15 or so set up questions and the only way I can think of bringing them out of the function to be used in another one and also import them into the global scope so they can be used by the program, is to use return is there another way to do this or would I just have to use return for every variable

谢谢

# Settings file, if user chooses to run setup this is all the setup 
questions
def gameSettingsSetup():
   print("Lets setup")
   numPlayers = int(input("How many real players are playing: "))
   numAIplayers = int(input("How many AI players will be playing?: 
   "))
   AILevel = input("What AI difficulty level would you like?: ") 

# Game settings all the main game settings

# sends over the settings into the text file
def gameSettingsSave():

推荐答案

您可以做到

return numPlayers, numAIplayers, AILevel

,但是将所有设置存储在字典中可能会更容易:

but it might be easier to store all of your settings in a dictionary:

def gameSettingsSetup():
    print("Lets setup")
    settings = {}
    settings["numPlayers"] = int(input("How many real players are playing: "))
    setting["numAIplayers"] = int(input("How many AI players will be playing?: "))
    settings["AILevel"] = input("What AI difficulty level would you like?: ")
    return settings

然后,您可以将 settings 字典传递给需要它的任何函数,也可以轻松地将其全部保存到磁盘中.

Then you can pass the settings dictionary to whichever functions need it and also easily save it all to disk.

这篇关于如何将多个变量从一个函数移到全局范围?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆