Python practice questions: play rock-paper-scissors with the computer, keep playing in a loop, you can manually exit, and you can calculate the player's winning rate after launch

A random number module is used in this problem

Program idea: Use numbers 1~3 to represent rock-paper-scissors respectively, use random numbers to make the computer play the game, the player makes an input, and judges whether to win or lose. , the game is over, calculate the player's winning percentage

Below is the code directly:

import random

def play_game():
    #总把数
    count=0
    #胜率把数
    player_win=0
    while True:
        computer=random.randint(1,3)
        player=int(input('请输入数字:1,剪刀,2,石头,3,布,0,手动退出'))
        #手动退出游戏
        if player==0:
            #判断一次没玩就退出游戏
            if count==0:
                print('您还没开始游戏呢')
                break
            print('游戏结束')
            print('玩家玩了{}把,赢了{}把,胜率:{}%' .format(count,player_win,player_win/count*100))
            break
        elif player not in (1,2,3):
            print('请输入1-3之间的数')
            #增加换行,美化显示效果
            print()
            continue
        #把数计数
        count+=1
        print('电脑出拳为:{}'.format(computer))
        if player==computer-1 or player==computer+2:
            print('玩家胜利')
            player_win+=1
        elif player==computer:
            print('平局')
        else:
            print('电脑胜利')
        print()


play_game()

 This topic is easy, a good exercise for beginners, and a deeper understanding of python

Guess you like

Origin blog.csdn.net/qq_61380148/article/details/125811346