2017-08-06 61 views
1

我創造了一種方法來獲得板球比賽的折騰。我需要從toss()使用該結果在另一個溫控功能的結果()如何將函數的結果用作數據到另一個?

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

首先,你必須return結果從拋起然後分配到你作爲參數傳遞給一個變量在if語句conditon使用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

感謝 但我需要的,如果折騰是蝙蝠顯示運行,但在這裏它不 –

+0

這是因爲'myToss'是'None',它根本就不能算是別的。檢查我的答案。 – Unatiel

0

因此,首先,你的函數應該採取一個參數tos。使用全局變量可能會導致麻煩,應儘可能避免

另外,您正在設置toss()函數中的r變量。這意味着r只存在於toss()的範圍內,並且在其外部不可用。

其次,即使r是一個全局變量集toss(),因爲print不返回任何東西,r永遠是None。您必須刪除print。三,不要使用全局變量來獲取函數的輸出(除非你真的需要)。相反,你應該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")))) 
相關問題