Same results after the same loop

Viewed 35

I'm learning Python from Udemy. I had a problem with a while loop.

My question is: why the indentation of the first print changes the result?

1) First loop. Correct:

import random


playerhp = 300
enemyatkl = 60
enemyatkh = 80


while playerhp > 0:
    dmg = random.randrange(enemyatkl, enemyatkh)
    playerhp = playerhp - dmg


    if playerhp <= 10:
        playerhp = 10

    #THIS ONE
    print("Enemy strikes for: ", dmg, ". And your heath is: ", playerhp)


    if playerhp == 10:
        print("You have low health. You've been teleported")

        break

Results:

Enemy strikes for: 68 . And your heath is: 232

Enemy strikes for: 66 . And your heath is: 166

Enemy strikes for: 78 . And your heath is: 88

Enemy strikes for: 67 . And your heath is: 30

You have low health. You've been teleported

2) Second loop. Wrong print.

import random


playerhp = 300
enemyatkl = 60
enemyatkh = 80


while playerhp > 0:
    dmg = random.randrange(enemyatkl, enemyatkh)
    playerhp = playerhp - dmg


    if playerhp <= 10:
        playerhp = 10

        #THIS ONE
        print("Enemy strikes for: ", dmg, ". And your heath is: ", playerhp)


    if playerhp == 10:
        print("You have low health. You've been teleported")

        break

Results:

Enemy strikes for: 71 . And your heath is: 10

You have low health. You've been teleported.

The results are different. Why does this happen? I understand that the indentation plays a vital role but I can't fully comprehend the reason. Thank you in advance.

1 Answers

In python there are no {} curly brackets to identify code blocks, when you change indentation you move your code to inner or outer block

So the difference between

if playerhp <= 10:
    playerhp = 10
    print("Enemy strikes for: ", dmg, ". And your heath is: ", playerhp)

And

if playerhp <= 10:
    playerhp = 10
print("Enemy strikes for: ", dmg, ". And your heath is: ", playerhp)

Could be seen as the difference between

if (playerhp>=10){
   playerhp=10;
   print ...
}

and

if (playerhp>=10){
   playerhp=10; 
}
print ...
Related