[英]Looking to add a function that will terminate the program by typing 'exit'
現在,我的工作代碼成功地詢問用戶是否願意在每次輸入后繼續使用該程序。 然而,我想做的是允許用戶隨時鍵入字符串“exit”來終止程序。 這樣我就不需要在每次輸入后詢問用戶,而是可以在開始時放置一個打印行,讓他們知道隨時鍵入“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
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.