核心知识&大纲:
课程目录:
课程介绍
一次猜测
支持多次猜测-while循环
限制猜测次数-for循环
通过argv指定猜测次数
记录猜测时间
支持多轮游戏
用tuple记录每轮的数据
显示每轮的数据
用lambda显示最快记录和最慢记录
for循环详解
基于列表的循环
基于range的循环
循环继续
循环退出
毕套循环
一次性退出嵌套循环
显示循环的index和值
到底可以基于什么循环
实现一个自己的可循环类
命名规范初步
重构出函数
猜数字游戏第二级-多节
函数详解-多节
错误和异常详解-多节
猜测程序
while
import random
answer = random.randint(1,10)
guess_limit = 3#最大猜测次数
guess_count = 0#当前猜测次数
while(guess_count < guess_limit):
guess = eval(input('1-10之间数字,猜猜?'))
if(answer == guess):
print('guess Right!')
print('game over! 88')
break;
elif(guess > answer):
print('Too Big!',end='')
else:
print('Too Small!',end='')
guess_count += 1
if(guess_limit == guess_count):
print('你已经用完猜测次数:' + str(guess_limit))
print('You Have Failed!')
break
else:
print('Guess Please!')
for
import random
answer = random.randint(1,10)
guess_limit = 3#最大猜测次数
is_right = False
for i in range(3):
guess = eval(input('1-10之间数字,猜猜?'))
if(answer == guess):
is_right = True
break
elif(guess > answer):
print('Too Big!',end='')
else:
print('Too Small!',end='')
if(i < guess_limit-1):
print('Guess Please!')
if(is_right):
print(f'You Have Win!The answer is {answer}')
else:
print('你已经用完猜测次数:' + str(guess_limit))
print('You Have Failed!')
第一阶段代码
#支持输入猜测次数
#支持时间记录 used_time = end_time - start_time
#支持多轮游戏 while if break
#tuple 元组 记录每局数据 .append((cycle,is_right,used_time))
#三元运算替代 label = 'WIN' if(_is_right) else 'FAIL'
#lambda best_score = min(score,key=lambda x:x[2])
#lambda best_score = min(score,key=lambda x:x[2] if x[1] else 9999)
#try except 异常处理-有异常即捕获
#异常处理 对症下药
import random
import sys
import time
try:
guess_limit = int(sys.argv[1])#指定最大猜测次数
#print(a)
except ValueError:#异常处理模块
guess_limit = 4 #默认最大输入次数4
print('输入次数有错,使用默认值:4')
except NameError:
print('name error ignore')
score = []#分数
cycle = 0#第几轮
while(True):
cycle += 1
begin_time = time.time()
answer = random.randint(1,10)
is_right = False
for i in range(guess_limit):
try:
guess = eval(input('1-10之间数字,猜猜?'))
except NameError:
print('别乱说,输入1-10之间的数字')
continue
if(answer == guess):
is_right = True
break
elif(guess > answer):
print('Too Big!',end='')
else:
print('Too Small!',end='')
if(i < guess_limit-1):
print('Guess Please!')
if(is_right):
print(f'You Have Win!The answer is {answer}')
else:
print('你已经用完猜测次数:' + str(guess_limit))
print('You Have Failed!')
end_time = time.time()
used_time = round((end_time - begin_time),2)
print(f'共用时{used_time}')
#保存战绩
score.append((cycle,is_right,used_time))
best_score = min(score,key=lambda x:x[2] if x[1] else 9999)
con = input('是否继续,按q退出')
if (con == 'q'):
print('============战绩============')
for _cycle,_is_right,_used_time in score:
best_label = ' best' if(_cycle == best_score[0] and best_score[1]) else ''#设定最好的标记
label = 'WIN' if(_is_right) else 'FAIL'
print(f'{_cycle}轮,{label},{_used_time}{best_label}')
print('============战绩============')
break