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

如何为Python选民注册程序添加输入'exit'随时终止功能?

优化后的选民注册程序(支持随时输入exit退出)

功能说明

  • 程序启动时提示用户:输入exit可在任意环节终止程序
  • 移除原有的每次输入后询问是否继续的逻辑
  • 完整保留原有的姓名、年龄、公民身份、州缩写、邮编等验证规则
  • 任意输入步骤中输入exit,程序立即退出并提示

完整代码

import sys

# 全局配置变量
min_zip = "00001"
max_zip = "99999"
Y = ["YES", "Y"]
oldest_age = 100  # 原程序未定义,补充默认值
# 美国50个州缩写集合
state_abb = {
    "AL", "AK", "AZ", "AR", "CA", "CO", "CT", "DE", "FL", "GA",
    "HI", "ID", "IL", "IN", "IA", "KS", "KY", "LA", "ME", "MD",
    "MA", "MI", "MN", "MS", "MO", "MT", "NE", "NV", "NH", "NJ",
    "NM", "NY", "NC", "ND", "OH", "OK", "OR", "PA", "RI", "SC",
    "SD", "TN", "TX", "UT", "VT", "VA", "WA", "WV", "WI", "WY"
}

def get_input_with_exit(prompt, validator=None):
    """通用输入处理函数:检查exit退出,验证输入合法性"""
    while True:
        user_input = input(prompt).strip()
        # 检查是否输入exit
        if user_input.lower() == "exit":
            print("Exiting program.")
            sys.exit(0)
        # 如果有验证函数,验证输入是否合法
        if validator is None or validator(user_input):
            return user_input
        # 验证不通过时提示重新输入
        print("Invalid input, please try again.")

def main():
    # 程序启动提示
    print("****************************************************************")
    print("Welcome to the Python Voter Registration Application.")
    print("Tip: You can enter 'exit' at any time to terminate the program.")
    print("****************************************************************")

    # 获取并验证姓名(仅允许字母)
    f_name = get_input_with_exit("What is your first name? ", lambda x: x.isalpha())
    l_name = get_input_with_exit("What is your last name? ", lambda x: x.isalpha())

    # 获取并验证年龄(18-100岁)
    def age_validator(input_str):
        try:
            age = float(input_str)
            return 0 <= age <= oldest_age
        except ValueError:
            return False
    age_input = get_input_with_exit("What is your age? (18-100) ", age_validator)
    age = float(age_input)
    if age < 18:
        print("You are not old enough to vote. Exiting program.")
        sys.exit(0)

    # 验证公民身份
    citizen = get_input_with_exit("Are you a U.S. Citizen? ")
    if citizen.upper() not in Y:
        print("You are not a U.S. Citizen. Exiting program.")
        sys.exit(0)

    # 验证州缩写
    state = get_input_with_exit("What state do you live? (ex. Texas = TX) ", 
                               lambda x: x.upper() in state_abb).upper()

    # 验证邮编
    def zip_validator(input_str):
        if input_str.isdigit():
            return int(min_zip) <= int(input_str) <= int(max_zip)
        return False
    zipcode = get_input_with_exit("What is your zipcode? ", zip_validator)

    # 输出注册信息
    print("\nThank you for registering to vote. Here is the information we received: ")
    print(f"Name: {f_name} {l_name}")
    print(f"Age: {int(age)}")
    print(f"U.S. citizen: {citizen}")
    print(f"State: {state}")
    print(f"Zipcode: {zipcode}")
    print("Thanks for trying the Voter Registration Application. Your voter",
          "registration card should be shipped within 3 weeks.")
    print("****************************************************************")

if __name__ == "__main__":
    main()

关键改动说明

  1. 新增通用输入函数:get_input_with_exit 封装了「检查exit退出」和「输入验证」逻辑,避免重复代码,让每个输入环节都具备exit退出能力。
  2. 移除冗余函数:删除原有的cont_confirm函数,不再需要每次输入后询问是否继续。
  3. 启动提示:在程序开头添加明确提示,告知用户可输入exit随时退出。
  4. 补全局变量:原程序中未定义的oldest_age和state_abb,补充了默认值和完整的美国州缩写集合,确保程序可直接运行。
  5. 保留原有验证:所有原有的输入验证逻辑(姓名字母、年龄范围、公民身份、州缩写、邮编规则)均完整保留,仅通过lambda或自定义函数传入通用输入函数实现。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 18:54:22