如果输入为no,如何在Python中重启程序?
当输入为=no,询问这个语句是否正确时,程序就结束了,但我想让它从头开始重新运行,这个是在VS Code上用Python写的。
while True:
product = input("Enter product name: ")
price = float(input("What is the price of the product: "))
print(f'''You want to save towards purchasing {product.title()} which costs {price} dollars(Can)''')
correct = input ("Is this correct, Yes or No: ")
if correct == "no":
print("Re-enter correct data")
if correct == "yes":
add_a_second_product = input("would you like to add a second product, Yes or No: ")
if add_a_second_product == "no":
current_saved = float(input("How much money do you currently have saved: "))
print(f'''You need {round(price-current_saved,2)} more dollars''')
if current_saved >= price:
print(f'''you have {current_saved} dollars which is enough to purchase {product} for {price}$''')
if add_a_second_product == "yes":
product2 = input("Enter second product name: ")
price2 = float(input("What is the price of the second product: "))
print(f'''You want to save towards purchasing {product.title()} and {product2.title()} which costs {round(price+price2,2)} dollars(Can)''')
correct2 = input ("is this correct, Yes or No: ")
if correct2 == "no":
print("Re-enter correct data")
if correct2 == "yes":
current_saved2 = float(input("How much do you currently have saved: "))
print(f'''You need {round(price+price2-current_saved2,2)} more dollars''')
if current_saved2 >= price:
print(f'''you have {current_saved2} dollars which is enough to purchase {product} for {price}$''')
if current_saved2-price >= price2:
print(f'''you have {current_saved2} dollars which is enough to purchase {product2} for {price2}$''')
exit()
我试着在里面用break命令,但那样只是让整个程序停止了。我还试着把continue和break一起用,但continue只是重新运行了尝试的部分。我可能用错了这些命令,但我也不太清楚,因为我才学习Python大约一周。
1 个回答
2
你需要在执行到 print("Re-enter correct data")
这行代码后,立刻回到 while
的开头。
...
if correct == "no":
print("Re-enter correct data")
continue
if correct == "yes":
...