2016-10-29 59 views
0

我想知道如何從def getInput中使用「adj」變量並將其連接到形容詞(),我試圖讓它可以從用戶那裏獲得輸入,然後根據如何激活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 
+0

你在哪裏要使用的價值?你真的需要'getInput'函數嗎? –

+0

用參數定義'''形容詞'''def形容詞(adj):...''',從'''getInput''返回adj,將返回值傳遞給'''形容詞' ''。 https://docs.python.org/3/tutorial/controlflow.html#defining-functions – wwii

+0

您可以返回「多個」值:'return insult,target,adj'它不是真的*多個值,它是一個元組,但你可以像這樣調用函數:'insult,target,adj = getInput()'。 – cdarke

回答

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關鍵字在函數內部,或者乾脆宣佈在全球範圍內的數值開始與

0

如果你想在getInput的「ADJ」變量的值( )並在形容詞()中使用它,你會想從getInput()返回它,然後你可以調用getInput()。如果在getInput()的末尾添加行return adj,然後在另一個函數(如adjective())中添加行即可在該函數中使用它。

一般來說,你可以從函數返回值和作爲函數的參數之間的共享價值觀傳遞值 - Python的文檔解釋瞭如何工作的: https://docs.python.org/2/tutorial/controlflow.html#defining-functions

相關問題