首页 > 解决方案 > 为什么我的分支条件不执行?而且,我如何让程序重复自己?

问题描述

我正在尝试为 MIT OCW 做作业(这是一门自我发展课程,而不是学分课程,所以别担心,我没有作弊)。

这是我到目前为止所拥有的:

#This program calculates how many months it will take to buy my dream home 
print("Welcome to the dream home calculator.")
total_cost=input("To start, please write down the cost of your dream home. Use only numbers, and do not use commas.\n")

try: 
  float(total_cost)

  if total_cost>1000000:
   print("That's quite a pricey home!")
  elif total_cost>=200000:
   print("That's a decently-priced home.")
  else:
   print("Are you sure you entered an actual home value in the Bay area?")

except:
  print("Please enter only a number, with no commas.")
  total_cost

但是,无论我输入什么数字,我都没有得到任何文本,例如“那是一个价格合理的房子”,程序直接进入“请只输入一个数字,不要输入逗号”。

此外,如果用户输入的不是数字,我希望程序再次询问房屋的总成本。我如何让它做到这一点?

谢谢!

编辑:没关系!我想到了!float(total_cost) 实际上并没有将 total_cost 转换为浮点数。为了解决这个问题,我做了: total_cost=float(total_cost)

不过,第二个问题呢?

标签: pythonloopsbranch

解决方案


关于第二个问题,您可以尝试使用while循环。

# This program calculates how many months it will take to buy my dream home
print("Welcome to the dream home calculator.")
input_flag = False
while input_flag == False:
    total_cost = input(
        "To start, please write down the cost of your dream home. Use only numbers, and do not use commas.\n")
    # if the total_cost is a number string, the input_flag will become True
    # Then it will escape the loop
    input_flag = total_cost.isnumeric()

try:
    total_cost = float(total_cost)

    if total_cost > 1000000:
        print("That's quite a pricey home!")
    elif total_cost >= 200000:
        print("That's a decently-priced home.")
    else:
        print("Are you sure you entered an actual home value in the Bay area?")

except:
    print("Please enter only a number, with no commas.")
    total_cost

推荐阅读