2017-08-06 72 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")))) 
相关问题