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

多个if语句如何搭配单个else 实现登录校验同时缩短代码长度

登录校验代码优化方案

你原有逻辑是符合需求的,要同时输出所有错误确实不能用elif。可以通过将校验条件和对应的错误提示绑定为可遍历的序列,避免重复书写判断语句,后续新增校验规则也更方便:

# 校验规则与对应错误提示配对,统一维护
check_list = [
    (is_email(email), "邮箱格式无效"),
    (is_name(name), "用户名格式无效"),
    (password == confirmPassword, "两次输入密码不一致"),
    (is_secure(password), "密码安全度不足"),
]

errors = [msg for check_pass, msg in check_list if not check_pass]
if errors:
    for err in errors:
        print(err)
else:
    print("Success")

如果追求更短的写法,也可以简化为:

errors = []
if not is_email(email): errors.append('邮箱格式无效')
if not is_name(name): errors.append('用户名格式无效')
if password != confirmPassword: errors.append('两次输入密码不一致')
if not is_secure(password): errors.append('密码安全度不足')
print('\n'.join(errors) if errors else 'Success')

两种写法都保留了「一次性输出所有错误」的逻辑,也满足无错误时才输出Success的需求,比原代码更简洁易维护。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 09:57:01