Home > Net >  how to stop the loop in while in python?
how to stop the loop in while in python?

Time:10-26

i tried to do a while loop in which after the user inputs 'no' then the loop will stop and end the program but it did not work and i can't find the problem

finish = True
while (finish) :
    kg = float(input('Enter kg: '))
    total = kg * 2.2
    print('The converted kg is: ', total, 'lbs')
    question = input('do you want to quit?')
if question == 'Yes' or 'yes' or 'YES':
    finish = False
    print('Bye-Bye')
else :
    print('OK!')
    

this is the code and when the user typed 'no' it should end the program

CodePudding user response:

The problem here is that your identation is off. The if/else statement is not ran inside the loop but after it. Modify your code like so:

finish = True
while (finish) :
    kg = float(input('Enter kg: '))
    total = kg * 2.2
    print('The converted kg is: ', total, 'lbs')
    question = input('do you want to quit?')
    if question == 'Yes' or 'yes' or 'YES':
        finish = False
        print('Bye-Bye')
    else :
        print('OK!')

CodePudding user response:

As @Damian Robert said, the indentation on your if/else statements was off

However there are better ways to exit to loop, namely with a break statement inside the while loop

This exits the loop at its current iteration, meaning you don't need to set finish to be False, probably saving time as the program doesn't have to run another iteration of the loop and check the variable again. While this won't make any difference in a small script like this, it is best practise for future code

I have also changed the code regarding the user's input, it now should convert the str to lowercase then check if the letter y is present in the str - this just reduces the chance of the user inputting the response incorrectly

import sys

finish = True
while finish:
    kg = float(input('Enter kg: '))
    total = kg * 2.2
    print(f'The converted kg is: {total}lbs')
    question = input('Do you want to quit?')
    if 'y' in question.lower(): #converts str to lowercase to compare whether it contains the str 'y'
        #finish = False #not needed here unless you need to access it later in the script
        print('Bye-Bye!')
        break #exit the while loop
    else:
        print('OK!')
        continue #restart loop, not actually needed as will continue to next iteration naturally, but can improve readability

print('Exiting Program')
sys.exit(0) #program will end naturally here, so `sys.exit(0)` isn't really needed but it can improve readability

Hope this helps ツ

  • Related