所以我有一个python程序有多个可能的输入,对于这一部分,我试图打破while循环,询问“输入产品成本”但是,当用户输入有效成本时,它只是重新加载他们输入另一个成本而不是结束。
while True:
update_choice = input("What would you like to update? (c)ost or (q)uantity")
if update_choice == "c":
while True:
new_price_update = float(input("Enter a product cost: "))
if new_price_update > 0:
for i in range(0, len(product_names)):
if update_item == product_names[i]:
product_costs[i] = new_price_update
print("Product cost has been updated.")
break
else:
print("Invalid price. Please try again.")
答案 0 :(得分:0)
break
仅退出当前循环。由于你打破了内部最多的循环,这只退出这个。你最后进入第二次循环。
答案 1 :(得分:0)
while True:
new_price_update = float(input("Enter a product cost: "))
if new_price_update > 0:
for i in range(0, len(product_names)):
if update_item == product_names[i]:
product_costs[i] = new_price_update
print("Product cost has been updated.")
break
您正在使用双循环语句:
while True:
和for i in range...
。
break语句只会退出它所在的最里面的循环for
循环,但会继续在while True:
循环内循环,再次提示用户。
请改为尝试:
while True:
new_price_update = float(input("Enter a product cost: "))
if new_price_update > 0:
for i in range(0, len(product_names)):
if update_item == product_names[i]:
product_costs[i] = new_price_update
print("Product cost has been updated.")
break
break
答案 2 :(得分:0)
插入另一个break
来停止内部while True:
,因为break
语句只会停止for
语句,如下所示:
while True:
update_choice = input("What would you like to update? (c)ost or (q)uantity")
if update_choice == "c":
while True:
new_price_update = float(input("Enter a product cost: "))
if new_price_update > 0:
for i in range(0, len(product_names)):
if update_item == product_names[i]:
product_costs[i] = new_price_update
print("Product cost has been updated.")
break
else:
print("Invalid price. Please try again.")
break
答案 3 :(得分:0)
你的break
只会'打破'内部for循环。为了突破第二个while循环,你需要将break
放在for循环之外。
while True:
update_choice = input("What would you like to update? (c)ost or (q)uantity")
if update_choice == "c":
while True:
new_price_update = float(input("Enter a product cost: "))
if new_price_update > 0:
for i in range(0, len(product_names)):
if update_item == product_names[i]:
product_costs[i] = new_price_update
print("Product cost has been updated.")
break
else:
print("Invalid price. Please try again.")
答案 4 :(得分:0)
如果用户成功更新cost
后,您想要打破整个过程,请尝试使用此代码:
# while loop (1)
while True:
# flag to indicate updated successfully
updated = False
update_choice = input("What would you like to update? (c)ost or (q)uantity")
if update_choice == "c":
# while loop (2)
while True:
new_price_update = float(input("Enter a product cost: "))
if new_price_update > 0:
# for loop (1)
for i in range(0, len(product_names)):
if update_item == product_names[i]:
product_costs[i] = new_price_update
print("Product cost has been updated.")
updated = True
# break out from for loop (1)
break
else:
print("Invalid price. Please try again.")
if (updated == True):
# break out from while loop (2)
break
if (updated == True):
# break out from while loop (1)
break