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

时间:2019-01-30 11:46:47

标签: python for-loop if-statement

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()

如您所见,如果我的代码中的语句效率太低,请问如何才能将其最小化

2 个答案:

答案 0 :(得分:1)

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()

答案 1 :(得分:0)

您可以执行以下操作:

db = {'rockscissor': 1, 
 'rockpaper': 2, 
 'scissorrock': 2, 
 'scissorpaper': 1,
 'paperrock': 1, 
 'paperscissor': 2}

if choice1!=choice2:
    print("player {} is the winner, Congrats!!".format(db[choice1+choice2]
else:
    print("its a draw")

,您甚至还可以将抽奖添加到db

db = {'rockscissor': 1, 
 'rockpaper': 2, 
 'scissorrock': 2, 
 'scissorpaper': 1,
 'paperrock': 1, 
 'paperscissor': 2,
 'paperpaper':0,
 'rockrock':0,
 'scissorscissor':0
}

然后处理if

相关问题