2017-08-06 6 views
1

私はクリケットの試合のためのトスを得る方法を作成しました。私はあなたが投げるあなたがに引数として渡す変数にそれを割り当てるから結果をreturnしなければならないファンクションの結果をデータとして使用するにはどうすればよいですか?

import random 
tos = input("Choose head or tail \n") 
def toss(): 
    if tos == "head": 
      result = ["Bat", "Bowl"] 
      r =print(random.choice(result)) 
    elif tos == "tail": 
      result = ["Bat", "Bowl"] 
      r =print(random.choice(result)) 
    else: 
      print("ERROR!") 
toss() 
def result(): 
    # i need the value in toss either bat or bowl to be used in if 
    if r =="Bat": 
     runs = ["1" , "2","3","4","5","6","7","8","9","0","W",] 
     runs_2=print(random.choice(runs)) 

result() 

答えて

0

まず別のfucntion結果()でif文でconditonとして使用するtoss()からの結果を使用する必要がありますresult

import random 
tos = input("Choose head or tail \n") 
def toss(): 
    if tos == "head": 
     result = ["Bat", "Bowl"] 
     r =print(random.choice(result)) 
    return r 
elif tos == "tail": 
     result = ["Bat", "Bowl"] 
     r =print(random.choice(result)) 
    return r 
else: 
     print("ERROR!") 

myToss = toss()#instantiation of return from function 

def result(r) 
    if r =="Bat": 
     runs = ["1" , "2","3","4","5","6","7","8","9","0","W",] 
     runs_2=print(random.choice(runs)) 

result(myToss) #added parameter 
+0

おかげで しかし、私はトスがバットであれば実行を表示する必要があるが、ここでは 'myToss'は' NONE'が、それは単に何かすることはできないためです –

+0

をdoesntの。私の答えをチェックしてください。 – Unatiel

0

だからまず、あなたの関数はtosのためのパラメータを取る必要があります。グローバル変数を使用すると問題が発生する可能性があるため、可能であればを避けてください。

また、あなたはtoss()機能でr変数を設定しています。つまり、はtoss()のスコープにのみ存在し、その外では使用できなくなります。

printrは常にNoneなり、何も返さないので、rは、toss()に設定されたグローバル変数であっても第二に、。 printを削除する必要があります。

第3に、グローバル変数を使用して関数の出力を取得しないでください(が本当にになる必要があります)。代わりに、return何かが必要です。

def toss(tos): 
    result = ["Bat", "Bowl"] 
    if tos == "head": 
     r = random.choice(result) 
    elif tos == "tail": 
     r = random.choice(result) 
    else: 
     raise ValueError("You must choose 'head' or 'tail'") 
    print(r) 
    return r 

def result(this_is_NOT_r): 
    if this_is_NOT_r =="Bat": 
     runs = ["1" , "2","3","4","5","6","7","8","9","0","W",] 
     return random.choice(runs) 

print(result(toss(input("Choose head or tail \n")))) 
関連する問題