用python编程一个猜数字的小游戏

随机生成一个正整数(取值范围[1,100])。让用户猜数字,并给出相应的提示:如果用户输入比答案大,提示‘Too big, try again’;反之,提示‘Too small, try again’;如果猜中了,提示‘Congratulations!’。最后,要给出反馈(答案,猜的次数,猜的历史)。

img

import random

n = random.randint(1,100)

count = 0
history = []

while True:
    m = int(input("Please input your guess between 1 and 100, inclusively"))
    count += 1
    history.append(m)
    if m==n:
        print('Congratulations!')
        print('answer: %d' % m)
        break
    elif m>n:
        print('Too big, try again')
    else:
        print('Too small, try again')

print('statistics: %d times' % count)
print('history:', history)

img


import random
answer = random.sample(range(1, 101), 1)[0]

history = []
def f(answer):
    n = int(input('Please input your guess between 1 and 100, inclusively'))
    history.append(n)
    if n == answer:
        print('Congratulations!')
        print('answer: {}'.format(n))
        print('statistics: {} times'.format(len(history)))
        print('history: {}'.format(history))
        return 
       
    elif n > answer:
        print('Too big, try again')   
    elif n < answer:
        print('Too small, try again')
    return f(answer)
f(answer)
        

例:
Please input your guess between 1 and 100, inclusively15
Too small, try again
Please input your guess between 1 and 100, inclusively20
Too small, try again
Please input your guess between 1 and 100, inclusively30
Too small, try again
Please input your guess between 1 and 100, inclusively50
Too big, try again
Please input your guess between 1 and 100, inclusively48
Too big, try again
Please input your guess between 1 and 100, inclusively45
Too big, try again
Please input your guess between 1 and 100, inclusively39
Too big, try again
Please input your guess between 1 and 100, inclusively38
Too big, try again
Please input your guess between 1 and 100, inclusively37
Too big, try again
Please input your guess between 1 and 100, inclusively36
Too big, try again
Please input your guess between 1 and 100, inclusively32
Too small, try again
Please input your guess between 1 and 100, inclusively33
Too small, try again
Please input your guess between 1 and 100, inclusively34
Congratulations!
answer: 34
statistics: 13 times
history: [15, 20, 30, 50, 48, 45, 39, 38, 37, 36, 32, 33, 34]

img