红绿灯案例的介绍

1、对于需求的分析

2、创建类

3、实现红绿灯时间的输入和校验

4、时间红绿等的倒计时

5、设置红绿灯显示不同的颜色

6、实现数字的显示屏打印

import time # 让程序停止

import os # 清屏

from colorama import init,Fore,Back,Style # 导入颜色模块

init(autoreset=True) # 初始化 Colorama

class Light:
# 构造函数

def __init__(self):

self.light = []

# 自动初始化

self.prepare_light()

def prepare_light(self):
# 准备20行10列的200个灯

for row in range(20):
temp = [] # 每行10个

for col in range(10):
temp.append(False)
# 把每行的10个插入到Light集合中

self.light.append(temp)

class TrafficLight:

# 构造函数 --- 静态特征!!!

def __init__(self,green_time,yellow_time,red_time):
self.green_time = green_time # 绿灯的时间

self.yellow_time = yellow_time # 黄灯的时间

self.red_time = red_time # 红灯的时间

self.number01 = Light() # 显示第一个数字的电子屏

self.number02 = Light() # 显示第二个数字的电子屏

def build_LED_number(self,char:str):
"""

根据提供的数字来构建电子屏上的数字显示
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:param char: 提供的数字
:return: 返回构建的电子屏
"""
temp_LED = Light() # 新建一个电子屏幕! 后面修改这个电子屏

if char == "0": # 构建 “0”

for row in range(20):
for col in range(10):
if row < 2: # 最上面两行

temp_LED.light[row][col] = True

if row > 17: # 最下面两行

temp_LED.light[row][col] = True

if col < 2 : # 左边两列

temp_LED.light[row][col] = True

if col > 7: # 最后面两列

temp_LED.light[row][col] = True

elif char == "1":
for row in range(20):
for col in range(10):
if col > 7: # 最后面两列

temp_LED.light[row][col] = True

elif char == "2": # 构建数字2

for row in range(20):
for col in range(10):
if row < 2: # 最上面两行

temp_LED.light[row][col] = True

if col > 7 and row < 9:
temp_LED.light[row][col] = True

if row == 9 or row == 10:
temp_LED.light[row][col] = True

if col < 2 and row > 10:
temp_LED.light[row][col] = True

if row > 17:
temp_LED.light[row][col] = True

elif char == "3":
for row in range(20):
for col in range(10):
if row < 2: # 最上面两行

temp_LED.light[row][col] = True

if col > 7:
temp_LED.light[row][col] = True

if row == 9 or row == 10:
temp_LED.light[row][col] = True

if row > 17:
temp_LED.light[row][col] = True

elif char == "4":
for row in range(20):
for col in range(10):
if col < 2 and row < 9:
temp_LED.light[row][col] = True

if col > 7:
temp_LED.light[row][col] = True

if row == 9 or row == 10:
temp_LED.light[row][col] = True

elif char == "5":
for row in range(20):
for col in range(10):
if row < 2: # 最上面两行

temp_LED.light[row][col] = True

if col < 2 and row < 9:
temp_LED.light[row][col] = True

if row == 9 or row == 10:
temp_LED.light[row][col] = True

if col > 7 and row > 10:
temp_LED.light[row][col] = True

if row > 17:
temp_LED.light[row][col] = True

elif char == "6":
for row in range(20):
for col in range(10):
if row < 2: # 最上面两行

temp_LED.light[row][col] = True

if col < 2:
temp_LED.light[row][col] = True

if row == 9 or row == 10:
temp_LED.light[row][col] = True

if col > 7 and row > 10:
temp_LED.light[row][col] = True

if row > 17:
temp_LED.light[row][col] = True

elif char == "7":
for row in range(20):
for col in range(10):
if row < 2: # 最上面两行

temp_LED.light[row][col] = True

if col > 7:
temp_LED.light[row][col] = True

elif char == "8":
for row in range(20):
for col in range(10):
if row < 2: # 最上面两行

temp_LED.light[row][col] = True

if col < 2:
temp_LED.light[row][col] = True

if row > 17: # 最上面两行

temp_LED.light[row][col] = True

if col > 7:
temp_LED.light[row][col] = True

if row == 9 or row == 10:
temp_LED.light[row][col] = True

elif char == "9":
for row in range(20):
for col in range(10):
if row < 2: # 最上面两行

temp_LED.light[row][col] = True

if col < 2 and row < 9:
temp_LED.light[row][col] = True

if row > 17: # 最上面两行

temp_LED.light[row][col] = True

if col > 7:
temp_LED.light[row][col] = True

if row == 9 or row == 10:
temp_LED.light[row][col] = True

# 返回这个电子屏

return temp_LED

def print_LED(self,color:str):
"""

打印一个电子屏
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:return:
"""
for row in range(20):
# 打印第一个数字

for col01 in range(10):
if self.number01.light[row][col01] == True:
if color == "green":
print(Fore.GREEN + "●",end="")
elif color == "yellow":
print(Fore.YELLOW + "●", end="")
elif color == "red":
print(Fore.RED + "●", end="")
else:
print("○",end="")

print("\t",end="") # 两个数字间的空格!

# 打印第二个数字

for col02 in range(10):
if self.number02.light[row][col02] == True:
if color == "green":
print(Fore.GREEN + "●",end="")
elif color == "yellow":
print(Fore.YELLOW + "●", end="")
elif color == "red":
print(Fore.RED + "●", end="")
else:
print("○", end="")
# 换行!

print()

def start_display(self,number:int, color:str):
"""

把传递过来的数字有指定的颜色打印!
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:param number: 传递过来的数字
:param color: 指定的颜色
:return: 无
"""
# 把数字格式化

number_str = "%02d" % number
# 构建LED上显示的两个数字

self.number01 = self.build_LED_number(number_str[0])
self.number02 = self.build_LED_number(number_str[1])

# 在电子屏上展示

self.print_LED(color)

def start(self):
"""

开始红绿灯的倒计时!
~~~~~~~~~~~~~~~~~~~~~~~~~~`
:return:
"""
# 默认一直循环下去

while True:
# 绿灯

for number in range(self.green_time, -1, -1):
# 流程:打印数字 --》停止一秒钟 ---》清屏 ——————》打印减1后的数字

os.system("cls") # 请屏幕

self.start_display(number,"green") # 调用函数开始用特定的颜色打印

time.sleep(1) # 停止一秒钟

# 黄灯

for number in range(self.yellow_time, -1, -1):
# 流程:打印数字 --》停止一秒钟 ---》清屏 ——————》打印减1后的数字

os.system("cls") # 请屏幕

self.start_display(number, "yellow") # 调用函数开始用特定的颜色打印

time.sleep(1) # 停止一秒钟

# 红灯

for number in range(self.red_time, -1, -1):
# 流程:打印数字 --》停止一秒钟 ---》清屏 ——————》打印减1后的数字

os.system("cls") # 请屏幕

self.start_display(number, "red") # 调用函数开始用特定的颜色打印

time.sleep(1) # 停止一秒钟

@staticmethod # 静态方法,不需要实例化直接调用!!!!!!

def input_time(color:str):
"""

更具提供的颜色,输入相应的颜色的时间!
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~··
:param color: 提供的颜色
:return: 输入的时间
"""
time = "" # 定义一个全局的time

while True:
# 根据颜色提醒输入

if color.lower() in ["green","绿灯","绿","绿色"]:
print(Fore.GREEN + "请输入绿灯的时间:",end="")
time = input()
if color.lower() in ["yellow","黄灯"]:
print(Fore.YELLOW + "请输入黄灯的时间:", end="")
time = input()
if color.lower() in ["red", "红灯"]:
print(Fore.RED + "请输入红灯的时间:", end="")
time = input()

# 校验输入的是否符合要求: 数字 ,正数, 1-99

# 如果不符合要求怎么处理: ① 出现异常!系统退出,报错! ② 提醒重新输入

if not time.isdigit():
print("输入的值不符合要求【要求:1-99之间的数字】")
continue # 结束当前循环

else:
time_number = int(time)
if time_number < 1 or time_number > 99:
print("输入的值不符合要求【要求:1-99之间的数字】")
continue # 结束当前循环

else:
# 符合要求的

return time_number

if __name__ == "__main__":

# 输入红绿黄灯的时间

green_time = TrafficLight.input_time("green")
yellow_time = TrafficLight.input_time("yellow")
red_time = TrafficLight.input_time("red")
# 实例化

traffic01 = TrafficLight(green_time, yellow_time, red_time)
# 开始倒计时!

traffic01.start()

相关推荐:

Python Pandas 数据清洗实战案例

数据清洗是数据分析前最关键的一步,pandas提供处理缺失值、重复值、异常值、格式不一致和类型错误等工具,需结合业务逻辑分步迭代执行并验证。 数据清洗是数据分析前最关键的一步,Pandas提供了丰富且实用的工具来处理缺失值、重复值、异常值、格式不一致和类型错误等问题。下面通过一个贴近真实业务的销售订...

Python call 方法真实应用案例

__call__方法是让对象像函数一样被调用的关键机制,用于封装带状态的可调用单元、实现可配置行为、构建带状态的装饰器及统一回调接口,并自然兼容函数式工具链。 Python的__call__方法不是语法糖,而是让对象像函数一样被调用的关键机制——它在实际开发中广泛用于封装可配置行为、实现状态化函数、...

Python 深拷贝与浅拷贝区别及真实面试案例

浅拷贝只复制顶层对象,嵌套可变对象仍共享内存;深拷贝递归复制所有层级,完全隔离。dict.copy()是浅拷贝,修改嵌套项会影响原字典;性能敏感或含特殊对象时应避免深拷贝。 浅拷贝只复制顶层,嵌套对象仍共享 浅拷贝(如copy.copy()或切片[:])会创建新对象,但只复制最外层结构。如果原对象包...

Python 日志排查线上问题案例

线上问题排查,日志是第一手线索。Python项目中,日志写得不规范、不完整,或者关键信息缺失,会让定位问题变成“盲人摸象”。真正有效的日志,不是越多越好,而是该有的上下文都有、能还原执行路径、带可追溯标识、且不影响性能。 日志必须包含唯一请求ID 微服务或Web应用中,一次用户操作可能横跨多个模块甚...

Python 生产环境性能优化案例

python生产环境性能优化需先通过cprofile或py-spy定位瓶颈,再针对性改进:优先异步i/o、分层缓存、延迟导入及__slots__内存优化。 Python在生产环境中的性能问题,往往不是语言本身慢,而是代码写法、资源使用和部署方式没对齐真实场景。优化要从可观测性入手,先定位瓶颈,再针对...

Python structural pattern matching 的重构案例

match语句不能替代if-elif链的场景是当模式需运行副作用逻辑或依赖外部变量判断时,因其仅支持结构匹配与简单守卫;字典匹配默认子集匹配易漏字段;类匹配须对齐__match_args__顺序;列表解包在编译期定长;且match无穷尽性检查。 match语句不能替代if-elif链的场景 当模式中...

Python anyio 的跨生态适配案例

不能直接替代,但可间接兼容:fastapi硬依赖asyncio运行时,anyio需显式指定backend="asyncio"才能安全调用asyncio库(如aiomysql),且仅限完全可控的子逻辑中使用。 anyio能不能直接替代asyncio在FastAPI里用 不能直接替代,但可以间接兼容。F...