如何在Python程序中使用循环并结束循环



关于Python程序中的循环,我需要您的帮助。谁能告诉我如何循环下面的程序,比如当我输入错误的值时,它会不断提示我重新输入值,直到它得到正确的值并移动到下一个状态。

我正在尝试"while"循环但不成功。

# Determine cleaning type
def CleaningType ():

while True:
# Prompt user to input Light or Complete cleaning type
cleanType = int(input("ntPlease select your cleaning type:n(1) Lightn(2) Completen"))
if (cleanType == 1):
cleanCost = 20
elif (cleanType == 2):
cleanCost = 40
else:
# Display error msg
print("t*** Invalid - Please re-enter your value...")
False
return (cleanType, cleanCost)
# Get number of rooms --------------------------------
def GetNumRooms ():

while True
# Prompt and get user reponse for number of rooms
numRooms = int(input('How many rooms would you like to be serviced (1-10)?n'))
if (numRooms > 0 and numRooms <= 3):
print("ntYour cleaning size is small which costs $15 per room")
roomCost = 10
elif (numRooms > 3 and numRooms <= 5):
print("ntYour cleaning size is small which costs $25 per room")
roomCost = 15
elif (numRooms > 5 and numRooms <= 10):
print("ntYour cleaning size is small which costs $35 per room")
roomCost = 20
False
return (numRooms, roomCost)

您可以使用break在提交当前答案之一时结束while循环。

可以使用break语句结束循环。另外,函数可以像这样调用自己:

# Determine cleaning type
def CleaningType ():

while True:
# Prompt user to input Light or Complete cleaning type
cleanType = int(input("ntPlease select your cleaning type:n(1) Lightn(2) Completen"))
if (cleanType == 1):
cleanCost = 20
break
elif (cleanType == 2):
cleanCost = 40
break
else:
# Display error msg
print("t*** Invalid - Please re-enter your value...")
CleaningType()
CleaningType()

最新更新