Python 为什么赢了';我的分支条件不能执行吗?那么,我如何让程序重复它自己呢?
我正在为麻省理工开放式课程做作业(这是一门自我发展课程,不是学分课程,所以别担心,我没有作弊) 这就是我到目前为止所做的:Python 为什么赢了';我的分支条件不能执行吗?那么,我如何让程序重复它自己呢?,python,loops,branch,Python,Loops,Branch,我正在为麻省理工开放式课程做作业(这是一门自我发展课程,不是学分课程,所以别担心,我没有作弊) 这就是我到目前为止所做的: #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
#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(totalcost)实际上并没有把totalcost变成一个浮点值。为了解决这个问题,我做了:总成本=浮动(总成本)
不过,第二个问题呢?关于第二个问题,您可以尝试使用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。。。除了
-块。由于您实际上只是在尝试将输入转换为float,因此最好将异常处理保持在尽可能窄的范围内。
现在,您可以确保在try之后有一个有效的浮点数。。。除了
-block之外,它使调试更加容易
还要注意,您的例外条款过于宽泛。如果要转换为float
,唯一需要关注的异常是ValueError
,因为如果float()
无法转换输入,就会引发该异常。
如果您只是将放在除之外的位置,您可能(在一些稍微复杂的情况下)实际捕获到另一个不应该被忽略的异常。这是Python吗?它看起来像Python。如果您想让对该语言感兴趣的人看到它,您应该使用适当的语言进行标记。