You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python中满足条件时如何清屏?以程序重启场景为例

在Python程序中实现运行后清屏并重启的功能

当开发Python程序(比如游戏)时,常需要在用户完成一次操作后询问是否继续。如果用户选择“是”,就得清除当前屏幕内容,重新启动程序流程,且不留下上一次的执行痕迹。以下是针对你给出的示例代码的优化方案:

原示例代码

def add(num1,num2):
    return num1 + num2

def enter_number():
    num1 = int(input("Enter First Number: "))
    num2 = int(input("Enter Second Number: "))

    print(add(num1,num2))

enter_number()

would_continue = input("Would you like to Continue? 'y' or 'n'")

if would_continue == 'y':
    #Way to Clear Screen?
    enter_number()
else:
    print("Goodbye, user :D")

解决方案

1. 实现跨平台清屏函数

不同操作系统的清屏命令不一样:Windows用cls,Linux和macOS用clear。借助os模块可以实现跨平台的清屏功能:

import os

def clear_screen():
    # 判断当前操作系统,执行对应清屏命令
    os.system('cls' if os.name == 'nt' else 'clear')

2. 优化程序循环逻辑

原代码仅支持一次递归调用,无法多次重复执行。改用while True循环可以实现无限次重复,直到用户选择退出。

完整优化代码

import os

def add(num1, num2):
    return num1 + num2

def clear_screen():
    os.system('cls' if os.name == 'nt' else 'clear')

def enter_number():
    num1 = int(input("请输入第一个数字:"))
    num2 = int(input("请输入第二个数字:"))
    print(add(num1, num2))

while True:
    enter_number()
    # 统一转换输入为小写,支持用户输入Y或y
    would_continue = input("是否继续?输入'y'继续,'n'退出:").lower()
    if would_continue == 'y':
        clear_screen()
    else:
        print("再见啦,用户 :D")
        break

关键说明

  • 跨平台兼容性:通过os.name判断系统类型,保证在Windows、Linux、macOS上都能正常清屏
  • 循环稳定性:用while循环替代递归,避免多次递归导致的栈溢出问题
  • 输入容错性:使用lower()方法统一处理输入,用户输入大写或小写的y都能被识别为继续操作

内容的提问来源于stack exchange,提问作者user22350735

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.12 21:12:48