简体   繁体   中英

how to use loops and end it in a Python program

I need your help regarding the loop in a Python program. Can anyone show me how to loop the program below, like when I enter a wrong value it will keep prompting me to re-enter the value until it gets the correct values and moves to the next state.

I am trying the "while" loop but unsuccessful.

# Determine cleaning type
def CleaningType ():
    
    while True:
        # Prompt user to input Light or Complete cleaning type
        cleanType = int(input("\n\tPlease select your cleaning type:\n(1) Light\n(2) Complete\n"))
        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("\n\tYour cleaning size is small which costs $15 per room")
        roomCost = 10
    elif (numRooms > 3 and numRooms <= 5):
        print("\n\tYour cleaning size is small which costs $25 per room")
        roomCost = 15
    elif (numRooms > 5 and numRooms <= 10):
        print("\n\tYour cleaning size is small which costs $35 per room")
        roomCost = 20
        False
    return (numRooms, roomCost)

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

You can use a break statement to end a loop. Also, a function can call itself, like this:

# Determine cleaning type
def CleaningType ():
    
    while True:
        # Prompt user to input Light or Complete cleaning type
        cleanType = int(input("\n\tPlease select your cleaning type:\n(1) Light\n(2) Complete\n"))
        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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM