在python中检查int与否并继续执行事务

2024-06-16 10:27:11 发布

您现在位置:Python中文网/ 问答频道 /正文

我是Python新手,尝试编写帐户应用程序时,有一个值“balance”,并且余额必须是整数,我添加了“try except blocks”,但是如果客户端插入了一个float或string,它如何重新开始请求余额。你知道吗

顺便问一下,有没有比“尝试除外”更有效的方法?你知道吗

  def __init__(self):
    self.balance = 0;
    self.savings = 0;
    self.savingsPercentage = 0;
    self.name = "The Dad";

theDad = Account();
print("Balance: ", theDad.balance)
print("Savings: ", theDad.savings);

addMoney = input("Add some amount: ");

while True:
  try:
    addM = int(addMoney);
    break
  except ValueError:
    print("Invalid...Please insert an integer...")
    addM = addMoney;
    break
if type(addM) == int: 
  theDad.balance = theDad.balance+addM;
  print("Last Balance: ", theDad.balance);
  theDad.savingsPercentage = int(input("What percent do you want to save? : "))
  savingBalanceAmount = (addM*theDad.savingsPercentage)/100;
  theDad.savings = theDad.savings+savingBalanceAmount;
  print("Balance Amount to Saving: ", savingBalanceAmount, "added on Savings..")
  theDad.balance = theDad.balance-savingBalanceAmount;
  print("Balance: ", theDad.balance);
  print("Savings: ", theDad.savings);
  print("........................");
  print("New Transaction.....");
  addMoney = input("Add some money: ");

  while True:
    try:
      addM = int(addMoney);
      break
    except ValueError:
      print("Invalid...Please insert an integer...")
      addM = addMoney;
      break
  if type(addM) == int:
    savingBalanceAmount = (addMoney*theDad.savingsPercentage)/100;
    theDad.savings = theDad.savings+savingBalanceAmount;
    theDad.balance = theDad.balance+(addMoney-savingBalanceAmount);      print("Balance Amount to Saving: ", savingBalanceAmount, "added on Savings..")
    print("New Savings Total is: ", theDad.savings, "Last Balance Total is: ", theDad.balance)
    print("Thank you..")
  else:
    print("Try again...")
else:
  print("Try again...")```

Thank you..

Tags: selfintprintbalancetrybreakexceptsavings
1条回答
网友
1楼 · 发布于 2024-06-16 10:27:11

如果用户必须输入一个整数,那么在该值为真之前不应该退出while循环。你知道吗

addMoney = input("Add some amount: ");

while True:
    addMoney = input("Add some amount: ");

    try:
        addM = int(addMoney);
        break
    except ValueError:
        print("Invalid...Please insert an integer...")

# No need to check if addM is an int; the previous loop guarantees it.
theDad.balance = theDad.balance+addM;
print("Last Balance: ", theDad.balance);
theDad.savingsPercentage = int(input("What percent do you want to save? : "))

如果没有例外,try块几乎没有成本。如果一个异常,那么捕获它是相对耗时的,但是在接近您可以期望的input的以下调用等待更多用户输入的时间量的地方,您可以忽略该开销。你知道吗

相关问题 更多 >