在函数之间传递变量 - python

时间:2014-08-22 17:12:37

标签: python function

from sys import exit


def start():

    name = raw_input("Players name?\n>> ")
#age is the variable to be passed

    age = raw_input("Players age?\n>> ")
    print "Greetings %s of %sth clan of time" % (name, age) 
    first_room()

def first_room():

    print "\nYou are in a room with a couple of doors.
    print" There is a door to your left and right.
    print "Which door do you take?"""

    first_room = raw_input(">> ")
    if first_room == "left":
        second_room()
    elif first_room == "right":
        third_room()
    else:
        dead("a bear in a near by room explodes and his leg blind sides you.")

def dead(why):

    print why, "Good blooper scene!"
    exit(0)

def second_room():

    print "a npc is here.!"
    print "he's mumbling to himself.\nyou catch a LOTR reference\n"
    print "Do you shout for his attention or flee?"
    next = raw_input(">> ")
    if next == "flee":
        first_room()
    elif next == "shout":
        print "Your shout catches his attention"
        dead("mistakes were made.")
    else:
        dead("a near by bear explosion takes you out.")

def third_room():

    print "There is a sleeping bear here"
    print "You light the wooden sword on fire and use a barrel"
    print "to preform a jump attack with your flaming sword!"
    print "CRITICAL HIT!"
    gold_room()

def gold_room():

    print "\nYou see loot!"
    print "How much do you make off with"
    **loot = raw_input(">> ")**
**#checks age (from start) vs loot**    

    if  loot <= age:
        print "you make away with %s gold!" %(loot)
        exit()
    elif loot > age:
        dead("the bears friend catches up to you. Too heavy to run.")
    else:
        dead("you stumble around until another bear explodes.")

    exit()
start ()

2 个答案:

答案 0 :(得分:1)

您可以定义名称和年龄作为属性的类。在本课程中,您可以在需要时为所有引用年龄属性的房间定义方法。

class Game( object ):
    def __init__(self, nameIn, ageIn):
        self.name = nameIn
        self.age = ageIn

    def gold_room(self):
        if loot <= self.age:
            # do something

myGame = Game( 'Peter' , 25 )
myGame.gold_room()

答案 1 :(得分:0)

你需要你的函数来获取参数:

def first_room(my_arg):
    print "\nYou are in a room with a couple of doors.
    print" There is a door to your left and right.
    print "Which door do you take?"""
    first_room = raw_input(">> ")
    if first_room == "left":
        second_room()
    elif first_room == "right":
        third_room()
    else:
        dead("a bear in a near by room explodes and his leg blind sides you.")

def start():

    name = raw_input("Players name?\n>> ")
#age is the variable to be passed

    age = raw_input("Players age?\n>> ")
    print "Greetings %s of %sth clan of time" % (name, age) 
    first_room(age) # pass age

您可以使用age函数中使用my_arg传递的first_room值。

def foo():
    age = 100
    foo1(age)
def foo1(my_arg):
    print (my_arg + 10)


print(foo())
110