相同循环后的结果相同

2024-09-27 23:23:33 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在向我的朋友学习Python。我有一个while循环的问题

我的问题是:为什么第一个print的缩进会改变结果

1)第一回路。正确:

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)第二回路。错误的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.

结果不同。为什么会这样?我知道压痕起着至关重要的作用,但我不能完全理解原因。 先谢谢你


Tags: andyouforyourifisrandomprint
1条回答
网友
1楼 · 发布于 2024-09-27 23:23:33

在python中,没有{}花括号来标识代码块,当您更改缩进时,您会将代码移到内部或外部块

所以

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

以及

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

可以看作是

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

以及

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

相关问题 更多 >

    热门问题