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

如何用Python实现激活密钥验证?现有代码逻辑问题求助

激活密钥验证功能的代码修改方案

原代码的问题在于:

  • 输入错误时,while循环仅打印提示就break,程序会继续执行后续代码,没有真正终止
  • 输入正确时,if块执行后程序直接继续,整体结构冗余且未明确区分验证成功/失败后的流程

修改后的代码通过sys.exit()在验证失败时直接终止程序,确保只有输入正确才会继续执行脚本:

import sys

activeKey = "ILoveCoding45"

enterActiveKey = input("Please enter the activation key down below:\n")
if activeKey == enterActiveKey:
    print("Activation key is successful.")
    # 在这里编写验证通过后要执行的脚本内容
else:
    print("Activation key is incorrect. Please re-run the program")
    sys.exit()  # 终止程序,后续代码不会执行

# 示例后续代码,仅验证通过时才会运行
print("脚本开始执行核心功能...")

说明:

  • 导入sys模块用于调用exit()方法终止程序
  • 使用if-else结构替代原有的冗余while循环,逻辑更清晰
  • 验证失败时,打印提示后立即终止程序;验证成功则继续执行后续代码

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 13:20:29