简体   繁体   中英

Python question How can I loop back my code?

Currently I have my code exiting when an error is detected for example it will exit if your income is inputted as a negative and will exit if your postcode is entered as a string. This is great but I need to be able to create a loop so it will give you another chance to re-enter your values without it exiting. Vey new to python and haven't figured it out. Any help would be very apricated :)

# Initalize the constants
TAX_RATE = 0.15
TAX_RATE_MARRIED = 0.14
STANDARD_DEDUCTION = 10000.0
DEPENDENT_DEDUCTION = 3000.0

# Request the inputs
taxFile = input("Enter your tax file number: ")
grossIncome = float(input("Enter the gross income: "))
if (grossIncome < 0):
    print("Your income cannot be negative", )
    exit()
numDependents = int(input("Enter the number of dependents: "))
firstName = input("Enter your first name: ")
lastName = input("Enter your last name: ")
marrigeStatus = input("Are you Married? True/False: ")
address = input("Enter your address: ")
try:
    postcode = int(input("Enter your postcode: "))
except:
    print("Invalid Postcode Input")
    exit()
# Compute the income tax
taxableIncome = grossIncome - STANDARD_DEDUCTION - numDependents * DEPENDENT_DEDUCTION
incomeTax = taxableIncome * TAX_RATE
incomeTaxMarried = taxableIncome * TAX_RATE_MARRIED

# Display the income tax
print("The tax file number is", taxFile)
print("Your employee information is", firstName, lastName)
print("Your address is", address, postcode)
print("Your total income for the annual year was $", grossIncome)
if marrigeStatus:
    print("Your total income tax is $" + str(round(incomeTaxMarried, 2)))
if not marrigeStatus:
    print("Your total income tax is $" + str(round(incomeTax, 2)))
print("Thank you for using the program please press enter to close the program")

Just use a while loop. Here's one example.

If you're using Python 3.8+, you can use assignment expression as

while (grossIncome:=float(input('Enter the gross income: ')))<0:
    print("Your income cannot be negative", )

Otherwise, you could do

while True:
    grossIncome = float(input("Enter the gross income: "))
    if (grossIncome < 0):
        print("Your income cannot be negative", )
    else:
        break

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM