我有以下代码,如果发生某种可能性,我希望它跳回到一行:
number_of_10ct = int(input("How many 10 Cent coins would you like to insert? "))
while number_of_10ct < 0:
number_of_10ct = int(input("Please enter a positive number."))
number_of_20ct = int(input("How many 20 Cent coins would you like to insert? "))
while number_of_20ct < 0:
number_of_20ct = int(input("Please enter a positive number."))
number_of_50ct = int(input("How many 50 Cent coins would you like to insert? "))
while number_of_50ct < 0:
number_of_50ct = int(input("Please enter a positive number."))
number_of_100ct = int(input("How many 1 Rand coins would you like to insert? "))
while number_of_100ct < 0:
number_of_100ct = int(input("Please enter a positive number."))
number_of_200ct = int(input("How many 2 Rand coins would you like to insert? "))
while number_of_200ct < 0:
number_of_200ct = int(input("Please enter a positive number."))
number_of_500ct = int(input("How many 5 Rand coins would you like to insert? "))
while number_of_500ct < 0:
number_of_500ct = int(input("Please enter a positive number."))
# Creating a variable to store the total amount of
# money inserted into the vending machine.
change = round(((number_of_10ct * 0.10) +
(number_of_20ct * 0.20) +
(number_of_50ct * 0.50) +
(number_of_100ct * 1.00) +
(number_of_200ct * 2.00) +
(number_of_500ct * 5.00)),
2)
# Informing the user how much they have entered in total.
print("\n")
print ('You have a credit of' ,change, 'ZAR')
while change > 0:
customer_choice = input(("What would you like to buy?"
"Type N when you are finished \n"))
if (customer_choice == "Kleiner Brauner" or
customer_choice == "kleiner brauner" and
change >= product_1_price):
print ("You have chosen a", product_1,
"these cost", product_1_price, "each,")
change = round((change - product_1_price),2)
print ("You have this much money remaining: R", change)
elif (customer_choice == "Kakao" or
customer_choice == "kakao" and
change >= product_2_price):
print ("You have chosen a", product_2,
"these cost", product_2_price, "each,")
change = round((change - product_2_price),2)
print ("You have this much money remaining: R", change)
elif customer_choice == "N" or customer_choice == "n":
break
elif change <= 0:
print ("You have run out of money.")
break
else:
print ("There has been an error or you may not have enough credit.")
我希望发生的事情是:如果change = round((change - product_1_price),2)
最终会被否定,那么我希望程序返回到顶部(number_of_10ct = int(input("How many 10 Cent coins would you like to insert? "))
)并允许用户输入更多“钱”
我该怎么做?
答案 0 :(得分:1)
您可以做的是将所有代码放在一个额外的while
循环中,该循环将继续运行,直到change
变为正数(因此您需要先将change
初始化为负值循环)。
change = -1
while change < 0:
# All the rest of your code (re-indented to be under this while loop)
这样,您将在更改设置为正常值后输入while change > 0
循环。一旦change
变为负数,那么您就会离开此循环并返回顶部,用户可以在其中添加硬币。
然后,如果客户在使用所有更改之前决定不购买任何内容,那么change
仍然是正面的,您将退出主while change < 0
循环。
答案 1 :(得分:1)
使用while
循环和continue
语句:
while True:
dostuff()
if goback():
continue # back to start of loop
else:
break # code after the loop