python写出1~100的猜数字游戏,有5次机会。
import random
number = random.randint(1, 100)
chance = 5
for guess_time in range(1, chance + 1):
num = int(input('请输入数字:'))
leftover_chance = chance - guess_time
if num == number:
print("恭喜你答对了!")
break
elif num < number:
if leftover_chance == 0:
print('{1}次机会用完,挑战失败。正确数字是{0}。'.format(number,chance))
break
print("小了,还有{0}次机会".format(leftover_chance))
elif num > number:
if leftover_chance == 0:
print('{1}次机会用完,挑战失败。正确数字是{0}。'.format(number,chance))
break
print("大了,还有{0}次机会".format(leftover_chance))