gpt4 book ai didi

python - 如何优化循环和条件语句?

转载 作者:行者123 更新时间:2023-12-01 08:23:44 25 4
gpt4 key购买 nike

winner = False

def player():
global winner
while winner==False:

print("player 1: please choose rock/paper/scissor !")
choice1 = input()
print("player 2: please choose rock/paper/scissor !")
choice2 = input()

if choice1!=choice2:
if choice1=="rock" and choice2=="scissor" :
print("player 1 is the winner, Congrats!!")

elif choice1=="rock" and choice2=="paper" :
print("player 2 is the winner, Congrats!!")

elif choice2=="rock" and choice1=="scissor" :
print("player 2 is the winner, Congrats!!")

elif choice2=="rock" and choice1=="paper" :
print("player 1 is the winner, Congrats!!")

elif choice1=="scissor" and choice2=="paper" :
print("player 1 is the winner, Congrats!!")

elif choice1=="paper" and choice2=="scissor" :
print("player 2 is the winner, Congrats!!")
else:
print("its a draw")


print("do you want to start a new game?,yes or no")
answer = input()
if answer=="yes":
print("lets start another game!")
winner = False
elif answer=="no":
print("see you next time!")
winner = True


player()

正如你所看到的,我的代码中有太多低效的 if 语句,如果可能的话,我如何才能最小化它们

最佳答案

def player():
while True:

print("player 1: please choose rock/paper/scissor !")
choice1 = input()
print("player 2: please choose rock/paper/scissor !")
choice2 = input()

beats = dict(
rock='scissor',
scissor='paper',
paper='rock',
)

if choice1 != choice2:
if beats[choice1] == choice2:
winner = 1
else:
winner = 2
print("player %s is the winner, Congrats!!" % winner)
else:
print("its a draw")

print("do you want to start a new game?,yes or no")
answer = input()
if answer == "yes":
print("lets start another game!")
else:
print("see you next time!")
break


player()

关于python - 如何优化循环和条件语句?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54439922/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com