Home > Mobile >  how to use loops and end it in a Python program
how to use loops and end it in a Python program

Time:07-12

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)

CodePudding user response:

You could use break to end the while loop when one of the current answers are submitted.

CodePudding user response:

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()
  • Related