我正在向我的朋友学习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.
结果不同。为什么会这样?我知道压痕起着至关重要的作用,但我不能完全理解原因。 先谢谢你
在python中,没有
{}
花括号来标识代码块,当您更改缩进时,您会将代码移到内部或外部块所以
以及
可以看作是
以及
相关问题 更多 >
编程相关推荐