我已经创造了一种方法来获得板球比赛的折腾。我需要使用toss()
的结果在另一个fucntion结果的if语句中用作条件()
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 :(得分:0)
首先你必须return
抛出的结果,然后将它分配给你作为参数传递给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
答案 1 :(得分:0)
首先,您的函数应该为tos
设置一个参数。使用全局变量可能会导致麻烦,应尽量避免 。
此外,您正在r
功能中设置toss()
变量。这意味着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"))))