Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python while (bool): [closed]

Tags:

python

logic

In this case:

swag = True
i = 0

while swag:
    i=i+1
    print(swag)
    if i == 3:
        swag = False

Will the while loop exit after 3 turns?

Does while swag - check if swag exists or if swag is True

like image 554
Rohit Rayudu Avatar asked May 16 '26 02:05

Rohit Rayudu


2 Answers

while swag: will run while swag is "truthy", which it will be while swag is True, and will not be when you set swag to False.

like image 146
Xymostech Avatar answered May 17 '26 14:05

Xymostech


Does while swag - check if swag exists or if swag is True

It checks if swag is True (or "truthy", I should say). And yes, the loop will exit after 3 iterations because i=i+1 must be executed 3 times until i == 3 and (by the if-statement) swag is set to False, at which point the loop will exit.

But why not check this yourself?

swag = True
i = 0

while swag:
    i=i+1
    print(swag)
    if i == 3:
        swag = False
True
True
True
like image 33
arshajii Avatar answered May 17 '26 15:05

arshajii



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!