[英]Why won't my branched conditions execute? And, how do I get the program to repeat itself?
I'm trying to do an assignment for MIT OCW (it's a self-development class, not a for-credit class, so don't worry, I'm not cheating on anything).我正在尝试为 MIT OCW 做作业(这是一个自我开发的 class,而不是信用 class,所以别担心,我没有作弊)。
This is what I have so far:这是我到目前为止所拥有的:
#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
But, no matter what number I input, I don't get any of the text such as "That's a decently-priced home" and the program goes straight to "Please enter only a number, with no commas."但是,无论我输入什么数字,我都没有得到任何文本,例如“那是一个价格合理的房子”,程序直接进入“请只输入一个数字,不要输入逗号”。
Also, if the user inputs something other than a number, I want the program to ask for the total cost of the home again.此外,如果用户输入的不是数字,我希望程序再次询问房屋的总成本。 How do I get it to do that?
我如何让它做到这一点?
Thank you!谢谢!
EDIT: NEVERMIND.编辑:没关系。 I figured it out, float(total_cost) didn't actually turn total_cost into a floating point: To solve that, I did: total_cost=float(total_cost)
我想通了,float(total_cost) 实际上并没有把 total_cost 变成浮点数:为了解决这个问题,我做到了: total_cost=float(total_cost)
Still, what about the second question?不过,第二个问题呢?
About the second question, you can try using a while loop.关于第二个问题,您可以尝试使用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
You could do it like that:你可以这样做:
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()
Notice that I moved the if-clauses out of the try... except
-block.请注意,我将 if 子句从
try... except
-block。 As you're actually just trying to convert the input to float, it's good practice to keep the exception-handling as narrow as possible.由于您实际上只是尝试将输入转换为浮点数,因此最好将异常处理保持在尽可能窄的范围内。 Now you can be sure that you have a valid floating-point number after the
try... except
-block, which makes debugging a lot easier.现在您可以确定在
try... except
-block 之后您有一个有效的浮点数,这使调试变得容易得多。
Also notice that your exception-clause was too broad.另请注意,您的例外条款过于宽泛。 If you're converting to
float
, the only exception you're concerned with is ValueError
, as that one is raised if float()
is unable to convert your input.如果您要转换为
float
,那么您关心的唯一异常是ValueError
,因为如果float()
无法转换您的输入,则会引发该异常。 If you just put except
, you might (in some cases that are a little more complex) actually catch a different exception that should not go unnoticed.如果你只是放
except
,你可能(在某些情况下更复杂一点)实际上捕获了一个不应该被 go 忽视的不同异常。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.