如何使用从一个用户定义函数到另一个用户定义函数的局部变量?

时间:2016-10-29 16:43:03

标签: python user-defined-functions

我想知道如何使用" adj"来自def getInput的变量并将其连接到形容词(),我试图使它成为我可以从用户获得输入然后根据用户输入的形容词激活random.choice。作为这个项目的学生,我只能使用用户定义的函数。

import random
def getInput():
    insult = input("Enter number of insults you want generated: ")
    target = input("Enter the targets name: ")
    adj = input("Enter number of adjectives you want in your insults: ")

def adjective():
    adjectives = ("aggressive", "cruel", "cynical", "deceitful", "foolish", "gullible", "harsh", "impatient", "impulsive", "moody", "narrow-minded", "obsessive", "ruthless", "selfish", "touchy")

    for adj in adjectives:
        print(random.choice(adjectives))
        break

2 个答案:

答案 0 :(得分:0)

这是一个选项。

import random
def getInput():
    insult = input("Enter number of insults you want generated: ")
    target = input("Enter the targets name: ")
    adj = input("Enter number of adjectives you want in your insults: ")
    return int(insult), int(target), int(adj) # cast to int and return 

def adjective(numAdj): # add a parameter 
    adjectives = ("aggressive", "cruel", "cynical", "deceitful", "foolish", "gullible", "harsh", "impatient", "impulsive", "moody", "narrow-minded", "obsessive", "ruthless", "selfish", "touchy")

    for i in range(numAdj): # use parameter
        print(random.choice(adjectives))
        # do not break the loop after one pass 

insult, target, adj = getInput() # get values 
adjective(adj) # pass in 

另一种选择是在函数中使用global关键字,或者只是在全局范围内声明您的数字值

答案 1 :(得分:0)

如果你想在getInput()中取“adj”变量的值并在形容词()中使用它,你将需要从getInput()返回它,然后你可以调用getInput()。如果您只是在getInput()的末尾添加行return adj,那么在另一个函数中 - 例如形容词() - 您可以使用赋值adj = getInput()在该函数中使用它。

通常,您可以从函数返回值并将值作为参数传递给函数之间共享值--Python的文档解释了它的工作原理: https://docs.python.org/2/tutorial/controlflow.html#defining-functions