以前写过,写得挺费劲。今天碰到这题目,再练练。😃
题目
运行效果
完整代码
#/usr/bin/nve python
# coding: utf-8
import random #加载随机数模块
import os
def guess_number():
'''猜正整数'''
#生成1~100的随机数
choice_n = random.randint(1, 100)
count = 0 #初始猜测次数
guess_list = [] #初始猜测列表
while True:
#输入猜测数字
while True:
l = os.system(r'clear') #清屏
print('\n'*3, '猜正整数'.rjust(18))
print('\n'*2, '请输入1~100的正整数。'.rjust(20))
guess_n = int(input('\n\n\n\n%s'%' 输入猜测数字:'))
if 1<=guess_n<=100:
#猜数正确,加入猜历史列表
guess_list.append(str(guess_n))
count += 1
break
else:
print('\n'*3, ' 输入错误!')
print('\n 请输入1~100的正整数。')
if guess_n>choice_n:
print('\n'*3, ' Too big, try again!')
input('\n\n\n%s'%'Any key continue...'.center(42))
elif guess_n<choice_n:
print('\n'*3, ' Too small, try again!')
input('\n\n\n%s'%'Any key continue...'.center(42))
elif guess_n==choice_n:
print('\n'*3, ' Congrntulations on!')
input('\n\n\n%s'%'Any key continue...'.center(42))
break
return guess_n, count, guess_list
#主程序
s = guess_number()
end_s ='''
您的答案是:%s
您共猜了%s次。
您的猜测历史:%s'''%(s[0], s[1], ",".join(s[2]))
print('\n\n%s'%('~'*42)) #打印分割线
print(end_s)
精品文章:
来源:老齐教室