希望添加一个函数,该函数将通过键入来终止程序'exit'



现在我有一个工作代码,它成功地询问用户在每次输入后是否愿意继续使用程序。然而,我想做的是允许用户键入字符串";退出";在任何时候终止程序。这样,我就不需要在每次输入后询问用户,而是可以在开始时放置一条打印线,让他们知道要键入";退出";随时退出。

min_zip = "00001"
max_zip = "99999"
Y = ["YES", "Y"]
def cont_confirm():
"""
Repeats after every question asking the user
if they would like to continue or not.
"""
proceed = input("Do you want to continue with the voter Registration? ")
if proceed.upper() not in Y:
print("Exiting program.")
sys.exit(0)
def main():
# Loading variables
f_name = ""
l_name = ""
age = oldest_age + 1
citizen = ""
state = ""
zipcode = -1
# Main body
print("****************************************************************")
print("Welcome to the Python Voter Registration Application.")
cont_confirm()
# Ensures name is alpha characters
while not f_name.isalpha():
f_name = input("What is your first name? ")
cont_confirm()
# Ensure name is alpha characters
while not l_name.isalpha():
l_name = input("What is your last name? ")
cont_confirm()
# Validates within age range 
while (age < 0 or age > oldest_age):
print("What is your age? (18-100) ")
age = float(input())
if age < 18:
print("You are not old enough to vote. Exiting program.")
sys.exit(0)
cont_confirm()
# Validates citizen status
citizen = input("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)
cont_confirm()
# Validates state residence and ensures the input matches one of the 50 U.S. state codes
while state not in state_abb:
state = str.upper(input("What state do you live? (ex. Texas = TX) "))
cont_confirm()
# Validates zipcode as a digit and ensures it is within the min/max
valid_zip = False
while not valid_zip:
zipcode = input("What is your zipcode? ")
if zipcode.isdigit():
if int(min_zip) <= int(zipcode) <= int(max_zip):
valid_zip = True
# Finally, prints all input info and ends.
print("Thank 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("****************************************************************")
main()
def input_with_exit(message):
i = input(message)
if i == "exit":
exit() # or sys.exit(0)
else:
return i

并将此方法之外的input的所有实例替换为input_with_exit

相关内容

  • 没有找到相关文章

最新更新