【问题标题】:Python question How can I loop back my code?Python 问题 如何循环回我的代码?
【发布时间】:2021-10-27 09:46:25
【问题描述】:

目前我的代码在检测到错误时退出,例如,如果您的收入输入为负数,它将退出,如果您的邮政编码作为字符串输入,它将退出。这很好,但我需要能够创建一个循环,这样它会给你另一个机会在不退出的情况下重新输入你的值。对python非常陌生,还没有弄清楚。任何帮助将不胜感激:)

# Initialize 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")

【问题讨论】:

标签: python python-3.x loops


【解决方案1】:

只需使用while 循环。这是一个例子。

如果你使用的是 Python 3.8+,你可以使用赋值表达式 as

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

否则,你可以这样做

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

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-07-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多