2016-10-29 5 views
0

def getInputの "adj"変数をどのように使って形容詞()に接続するのか、私はユーザーからの入力を得ることができるようにしようとしています。ユーザが入力する多くの形容詞。このプロジェクトの学生として、私はユーザー定義関数しか使用できません。あるユーザ定義関数のローカル変数を別のユーザ定義関数にどのように使用しますか?

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

'' 'adjective''を引数付きで定義する - def' '' '' '' '' ... '' '、' 'getInput'''からadjを返し、' '形容詞' 'に戻り値を渡します。 ''。 https://docs.python.org/3/tutorial/controlflow.html#defining-functions – wwii

+0

「複数の」値を返すことができます: 'return insult、target、adj'それは本当に*複数の値ではなく、そのタプル、 'insult、target、adj = getInput()'のように関数を呼び出すことができます。 – cdarke

答えて

0

ここに1つのオプションがあります。別のオプションは、関数内globalキーワードを使用して、または単にあなたがか、getInputで「ADJ」変数(の値を取りたい場合は、グローバルスコープであなたの番号の値が

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 

)を使用し、それを形容詞()で使用すると、getInput()から返すことになり、getInput()を呼び出すことができます。 getInput()の最後にreturn adj行を追加するだけで、別の関数(例えば、形容詞())に代入すると、adj = getInput()という代入を使用してその関数で使用することができます。

一般的に、あなたは、関数から値を返すことができますし、引数が関数間の値を共有するように値を渡す - Pythonのドキュメントは、これがどのように動作するかを説明します。あなたが値を使いたいん https://docs.python.org/2/tutorial/controlflow.html#defining-functions

関連する問題