Python 2.7.9 - 如何在变量中保存raw_input以便以后使用它?

时间:2015-04-10 20:11:18

标签: python class variables input user-input

这是我基于文字游戏的一些代码:

location_now = ""

class what_do:

    def whaat(self):
        interactions = what_do()
        print "*What will you do? Type help_ to see all the actions*"
        what = raw_input("")
        if what == "help_":
            print ' '.join(help_)
            interactions.whaat()
        if what == "travel":
            print "These are all the cities you can travel to:"
            mapje.map()
            travel = raw_input("To which city do you want to travel?(Takes 10 seconds)")
            if travel == locations[0] or travel == locations[1] or travel == locations[2] or travel == locations[3] or travel == locations[4] or travel == locations[5] or travel == locations[6] or travel == locations[7] or travel == locations[8]:
                print "You are now travelling to %s" % travel
                time.sleep(10)
                print "You are now in %s!" % travel
                location_now = travel
            else:
                print "That is no location in Skyrim!"
                interactions.whaat()

我希望将来自travel = raw_input等的输入存储并保存在变量location_now中(我在课前和课外创建)。我必须稍后在我的代码中使用该输入。

这个课程将重复进行,因为它是一种“你想接下来要做什么?”#39;所以如果第二次输入what = raw_input(""),则要求它,必须替换location_now = ""

中存储的早期输入

3 个答案:

答案 0 :(得分:1)

我相信如果再次使用location_now,您会担心raw_input()变量中存储的内容会被覆盖。 幸运的是,这种情况不会发生,如果您将raw_input()的结果存储在变量中,它将保持不变。

你是否面临任何使你得出结论的问题?

答案 1 :(得分:1)

我会将您的location_now变量移到班级" what_do"作为静态变量。 (Static class variables in Python

另外作为一个有用的提示,这一行

if travel == locations[0] or travel == locations[1] or travel == locations[2] or travel == locations[3] or travel == locations[4] or travel == locations[5] or travel == locations[6] or travel == locations[7] or travel == locations[8]:

可以缩减为

if travel in locations:

这将检查travel是否在位置列表中。只是一点点提示,以简化您的代码! Python不是很漂亮吗?

答案 2 :(得分:0)

在尝试为location_now分配新值时,在whaat()函数中,实际上是在创建一个名为location_now的新局部变量。您没有为全局location_now分配新值。

您需要在赋值之前将location_now声明为全局,以便实际为全局变量赋值。

global location_now
location_now = travel