【发布时间】:2019-10-24 00:10:31
【问题描述】:
我对 python 还很陌生,每当我运行我的脚本时,前两个函数 humanPlay() 和 computerPlay() 都会被调用两次。我不想要这个。
我注意到,当我在 setRules() 函数中注释掉 draw 变量时,程序可以正常运行。我不确定为什么 f"{computerPlay()}" 和 f"{humanPlay()}" 不打印返回值。
我还验证了py文件没有命名为Random,以防止模块自行导入。
import random
Player = "Player"
Computer = "Computer"
options = ["ROCK","PAPER","SCISSORS"]
def main():
def humanPlay():
response = input("Make a selection between Rock, Paper, Scissors: ", )
response.upper()
if response.upper() in options:
print(response.upper())
return response.upper()
else:
print(f"{response.upper()}, is not a valid selection")
return humanPlay()
def computerPlay():
print(random.choice(options))
return random.choice(options)
def setRules():
rockWin = "You Win! ROCK beats SCISSORS "
paperWin = "You Win! PAPER beats ROCK "
scissorsWin = "You Win! SCISSORS beats PAPER "
draw = print("It's a Draw!, computer selected", f"{computerPlay()}", "and you selected", f"{humanPlay()}")
#loser = print(f"You Lose! {humanPlay()}", f"can't beat {computerPlay()}")
humanPlay()
computerPlay()
setRules()
main()
理想情况下,draw 变量应该类似于以下内容:
It's a Draw!, computer selected ROCK and you selected ROCK
注意:我仍然需要为程序编写逻辑才能知道石头、纸和剪刀之间的区别。
现在我只想返回正确的值,而不是整个函数。
【问题讨论】:
-
它们运行两次,因为它们被调用了两次。您在
main的底部调用humanPlay和computerPlay,然后在setRules中再次调用它们。 -
您调用
humanPlay()和computerPlay(),然后调用setRules(),它本身调用这两个函数。您需要调用它们一次,将它们的结果保存在变量中,然后将这些变量传递给setRules(),以便它可以使用它们。 -
f"{computerPlay()}"和f"{humanPlay()}"调用函数。我认为这不是您想要的,但解决方案并不完全清楚。请发minimal reproducible example。 -
顺便说一句,两次调用
random.choice(options)会产生两种不同的选择,你知道的,对吗? -
main结构不正确。这 3 个函数不属于main。这三个函数中的每一个都应该做一些事情,它们应该从main中调用,但不能驻留在那里。
标签: python python-3.x