Search code examples
pythonif-statementwhile-loopnested

How do you nest a while loop inside of an if statement? (Python)


I'm still really new to Python. Like, I'm only on Chapter 4 level of new (with very little prior experience). I have no doubt that I'm jumping the gun in asking this, but I'm not confident in my abilities in programming, and this is just a curiosity.

I want to know how to put a while loop into an if statement. The text's example is a commission calculator, and I want to know how to loop the program until the condition needs to be either restarted or ended.

Here's the example code (with my additions as comments):

keepGoing = 'y'

while keepGoing == 'y':
    sales = float(input('Enter the amount of sales: '))
    commRate = float(input('Enter the commission rate: '))

    commission = sales * commRate

    print(f'The commission is ${commission:,.2f}.')

    keepGoing = input('Do you want to calculate another commission (Enter y for yes): ')
    #(Enter y for yes, or n for no)

#if keepGoing = 'y':
#    (I didn't put anything here because this is where I got stuck)
#else:
#    print('Thank you for using the commission calculator.')

I didn't really try anything, but the compiler/interpreter (I'll forever get them mixed up 🙃) came back with a syntax error.


Solution

  • Blocks in Python are defined by indentation, so if you want something to happen inside a while loop, it needs to be indented one level deeper than the while:

    keepGoing = 'y'
    while keepGoing == 'y':
        keepGoing = input('Do you want to calculate another commission (Enter y for yes): ')
        #(Enter y for yes, or n for no)
    
        if keepGoing = 'y':  # inside the while loop
            print('Okay, here we go again!')
        
    print('Thank you for using the commission calculator.')  # outside the while loop