我从Udemy那里学Python。我在with循环上出了问题。
我的问题是:为什么第一个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结果:
敌人攻击: 68。你的健康状况是: 232
敌人攻击: 66 .你的健康是: 166
敌人攻击: 78。你的健康状况是: 88
敌人攻击: 67。你的健康是: 30
你身体不好。你被传送了
( 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结果:
敌人攻击: 71 .你的健康是: 10
你身体不好。你被传送了。
结果是不同的。这一切为什么要发生?我知道压痕起着至关重要的作用,但我不能完全理解原因。提前谢谢你。
发布于 2019-10-17 06:26:43
在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 ...https://stackoverflow.com/questions/58426067
复制相似问题