微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

为什么我的分支条件不执行?而且,我如何让程序重复自己?

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

我正在尝试为 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)

那么,第二个问题呢?

解决方法

关于第二个问题,你可以尝试使用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
,

你可以这样做:

def main():
    """Calculate how many months it will take to buy my dream home."""
    print('Welcome to the dream home calculator.\n')

    # Ask for input
    print(
        'To start,please write down the cost of your dream home. '
        'Use only numbers,and do not use commas.'
    )
    while True:
        total_cost_str = input('>>')

        try:
            total_cost = float(total_cost_str)
        except ValueError:
            print("That's the wrong input,try again!")
            continue
        else:
            break

    # Evaluate result:
    if total_cost > 1_000_000:
        print("That's quite a pricey home!")
    elif total_cost >= 200_000:
        print("That's a decently-priced home.")
    else:
        print("Are you sure you entered an actual home value in the Bay area?")


if __name__ == '__main__':
    main()

请注意,我将 if 子句移出了 try ... except 块。由于您实际上只是试图将输入转换为浮点数,因此最好将异常处理保持在尽可能窄的范围内。 现在您可以确定try ... except 块之后有一个有效的浮点数,这使得调试更容易。

另请注意,您的例外条款过于宽泛。如果您要转换为 float,您需要担心的唯一例外是 ValueError,因为如果 float() 无法转换您的输入,则会引发该异常。 如果您只输入 except,您可能(在某些情况下稍微复杂一些)实际上会捕获不应被忽视的不同异常。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。