练习题——day3

day3:猜数字游戏。系统随机产生一个数,系统会根据玩家的猜测进行提示,玩家则可根据系统提示,对下一次的猜测进行适当调整。

程序如下:

import random
x = random.randint(1,100)
times = 1
while True:
    if times>5:
        print("已经到达5次了")
        break
    guess_num = input("请输入一个小于100的整数")
    try:
        if x>int(guess_num):
            print("猜小了")
            print("猜第"+str(times)+"次")
            times = times+1
        elif x

这是限定5次猜的程序,不限定次数会更加简单一些。这个程序还可以再次修改一下,因为它只能玩一次就退出程序了,可以给玩家一个选择,是否继续玩?

理解:
每个程序都可以用自定义函数来完成,并用好注释,参考书上的过程如下:

"""guess_ganme_fun
Guess Game with a function
in this project the guess game is recast using a function"""

import random

PROMPT = 'What is your guess?'

# New constants
QUIT = -1
QUIT_TEXT = 'q'
QUIT_MESSAGE = 'Thanks you for playing'
CONFIRM_QUIT_MESSAGE = 'Are you sure you want to quit (y/n)'

#New confirm_quit function
def confirm_quit():
    """Ask user to confirm that they want to quit
       defauit to yes
       Return TRUE or False """
    spam = input(CONFIRM_QUIT_MESSAGE)
    if spam == 'n':
        return False
    else:
        return True

def do_guess_round():
    """choose a random number,ask the user for a guess check whether the guess
    is true and repeat until the user is conrrect"""
    computer_number = random.randint(1,100)
    number_of_guesses = 0
    while True:
        players_guess = input(PROMPT)
        # new if clause to test against quit
        if players_guess == confirm_quit():
            return QUIT
        else:
            continue #that is ,do next round of loop
        number_of_guess = number_of_guess + 1
        if computer_number == int(number_of_guesses):
            print('Correct!')
            return number_of_guess
        elif computer_number > int(number_of_guesses):
            print('too small')
        else:
            print('too big')

total_rounds = 0
total_guesses =  0

while True:
    total_round = total_rounds + 1
    print('starting round number' + str(total_rounds))
    print('Let the guessing begin')
    this_round = do_guess_round()

    # New if condition to test against quit
    if this_round == QUIT:
        total_rounds = total_rounds - 1
        avg = str(total_guesses/float(total_rounds))
        if total_rounds ==0:
            stats_message = 'you conpleted no round,please try again'
        else:
            stats_message = 'You played '+str(total_rounds) + 'rounds,with an average of'+\
                            str(avg)
        break

你可能感兴趣的:(python习题)