【问题标题】:If else loop in python doesn't function properly如果 Python 中的 else 循环无法正常运行
【发布时间】:2020-01-31 05:25:41
【问题描述】:

所以我正在编写一个程序,该程序应该将 2 个数据输入作为 int 用于用户的债务。变量是debt1 和debt2。它应该将这两个值相加,然后根据用户的输入,它应该使用我创建的“if/else”循环给出特定的响应。问题是程序只打印出第一个“if”语句的响应,无论输入是什么,它总是打印出“你的债务高得危险”。我该如何纠正这个问题?

** 这是我的代码 **

Name = input("Please enter your name: ")

debt1 = int(input("Please enter your first debt amount: "))
debt2 = int(input("Please enter your second debt amount: "))

totalDebt = debt1+debt2
print("Your total debt is ", totalDebt)

if (totalDebt > 900,000):
    print("Your debt is dangerously high ", Name)

elif((totalDebt >= 450,000 and totalDebt < 900,000)):
    print("We can help you reduce your debt.")

else:
    print("Congratulations, you know how to manage debt.")

【问题讨论】:

  • 900,000 不是有效数字
  • 在 python 3 中,您可以使用 _ 代替 , 用于包含大量零的数字。 900_000 会起作用。

标签: python if-statement error-handling logic runtime-error


【解决方案1】:

不要在数字中使用逗号:

if totalDebt > 900000:
    print("Your debt is dangerously high ", Name)
elif (totalDebt >= 450000 and totalDebt < 900000):
    print("We can help you reduce your debt.")
else:
    print("Congratulations, you know how to manage debt.")

正如@rdas 所说,您可以将_ 用于长数字,而不是,

【讨论】:

  • 是的,逗号是主要问题,谢谢。当我去掉逗号而只留下零时,程序对于 elif 和 else 语句仍然没有意义。例如,当总债务少于 450,000 时;它会打印出“恭喜,您知道如何管理债务”,但它也会打印出第二个语句的结果,即“我们可以帮助您减少债务”,而当价值低于 450,000 时它不应该这样做
  • @Madridista94 你用的是什么输入法?您是在终端之类的外壳中执行此操作吗?
猜你喜欢
  • 2015-05-16
  • 1970-01-01
  • 1970-01-01
  • 2013-12-30
  • 2013-06-17
  • 1970-01-01
  • 2023-03-28
  • 1970-01-01
  • 2014-09-27
相关资源
最近更新 更多