python 猜数字游戏 & 自动猜测

it2022-05-05  204

python 猜数字游戏

人工判断电脑自动判断猜100次的平均成功次数

人工判断

import random secret = random.randint(1, 100) guess = 0 i = 0 while guess != secret: try: guess = int(input('\n'+'请输入1-100的数字:')) if guess > secret: i += 1 print('您输入的数字大了!') elif guess == secret: i += 1 print('恭喜,您用'+str(i)+'次猜对了!') else: i += 1 print('您输入的数字小了!!!') except: print('仅能输入数字!!!') input('\n'+'点击回车退出!')

电脑自动判断

import random secret = random.randint(1, 10000) print('测试数为:'+str(secret)+'\n') guess = random.randint(1, 10000) lat_guess = 1 max_guess = 10000 print('输入随机数:'+str(guess)) b = 1 while guess != secret: if guess > secret: b +=1 print('随机数字大了!'+'\n') max_guess = guess - 1 guess = random.randint(lat_guess,max_guess) print('输入随机数:'+str(guess)) else: b +=1 print('随机数字小了!'+'\n') lat_guess = guess + 1 guess = random.randint(lat_guess,max_guess) print('输入随机数:'+str(guess)) print('恭喜,您猜对了!') print('\n'+'电脑用了'+str(b)+'次猜对数字!') input('点击回车退出!')

猜100次的平均成功次数

import random def text(d): secret = random.randint(1, d) guess = random.randint(1, d) lat_guess = 1 max_guess = d a = 1 while guess != secret: if guess > secret: a += 1 max_guess = guess - 1 guess = random.randint(lat_guess, max_guess) else: a += 1 lat_guess = guess + 1 guess = random.randint(lat_guess, max_guess) return(a) if __name__ == '__main__': b = 0 d = int(input('输入猜测的最大数:')) for i in range(100): b += text(d) print('平均用'+str(b//100)+'次!') input('点击回车退出!')

最新回复(0)