初学Python,用Python实现简单的猜数字游戏,具体如下:
"""
随机生成一个1-100之间的数字,让用户来猜,当猜错时,会提示猜的数字是大还是小了,直到用户猜对,游戏结束。
"""
#随机生成一个整数(1-100)
import random
answer=random.randint(1,100)
#玩家输入数字
num=int(input("Please input the num(1-100):"))
#游戏是否继续确认
quit = True
while quit:
#进行对比
while num!=answer:
if num>answer:
num=int(input("The number is more, please input another num :"))
else:
num=int(input("The number is less, please input another num :"))
#答案正确,游戏结束
print("The random randint is %d and you get it .\nYou win this game !" %num)
#判定是否循环游戏
to_continue = input("Whether to continue, if you don't want to continue, please type Q.")
if to_continue.lower() == 'q':
quit = False
print('End!')
else:
num = int(input("Please input the num(1-100):"))
answer = random.randint(1,100)
如何实现自动给出确切的数字范围?
"""
Date:2018/12/28
Version:2.0
功能:自动给出确切的数字范围
"""
#随机生成一个整数(1-100)
import random
answer = random.randint(1,100)
num_list = [1, 100]
#玩家输入数字
num = int(input("Please input the num(1-100):"))
#游戏是否继续确认
quit = True
while quit:
#进行对比
while num != answer:
if num > answer:
num_list[1] = num
num = int(input("The number is more, please input another num({},{}):".format(num_list[0],num_list[1])))
else:
num_list[0] = num
num = int(input("The number is less, please input another num({},{}):".format(num_list[0], num_list[1])))
#答案正确,游戏结束
print("The random randint is %d and you get it .\nYou win this game !" %num)
#判定是否循环游戏
to_continue = input("Whether to continue, if you don't want to continue, please type Q.")
if to_continue.lower() == 'q':
quit = False
print('End!')
else:
num = int(input("Please input the num(1-100):"))
answer = random.randint(1,100)
num_list = [1,100]
菜鸟共勉。