在Python中,当变量达到while循环中的某些阈值时执行函数

在Python中,当变量达到while循环中的某些阈值时执行函数,python,function,loops,Python,Function,Loops,目前,假设我有一个变量分数,它每1秒持续添加一次。每次分数达到10的倍数(20、30、40、10等),一条语句在while循环中从另一个变量执行一次到减号。例如: def levelUp(score): if score % 10 ==0 and score != 0: height -= 2 return height 此函数在另一个循环中调用: while True: levelUp(score) 目的是让函数检查分数是否可以除以2,如果可以,则从高度减

目前,假设我有一个变量
分数
,它每1秒持续添加一次。每次分数达到10的倍数(20、30、40、10等),一条语句在while循环中从另一个变量执行一次到减号。例如:

def levelUp(score):
    if score % 10 ==0 and score != 0:
      height -= 2
    return height
此函数在另一个循环中调用:

while True: 
  levelUp(score)

目的是让函数检查分数是否可以除以2,如果可以,则从高度减去。函数不能在
的外部调用,而True:
循环除外,因为这本身就是添加到
score
变量的内容。有没有办法做到这一点?

因此,看起来
高度
是程序中其他地方定义的一个变量,我认为您需要如下内容:

def levelUp(score, height):
    if score % 10 == 0 and score != 0:
        height -= 2
    return height
height = levelUp(score, height)
然后,当您调用
levelUp
时,请使用以下命令:

def levelUp(score, height):
    if score % 10 == 0 and score != 0:
        height -= 2
    return height
height = levelUp(score, height)
在Python中,尝试从函数内部修改外部变量可能会有点棘手,最好避免这种模式。有关此类问题的更多信息,请参阅此问题和顶部答案:

您可以将
while
和函数组合为一个:

score = 0
height = 100
while True:
    if score % 10 == 0 and score!= 0:
        height -= 2
    score+=1
或者,您可以对功能执行以下操作:

def levelUp(score, height):
    if score % 10 == 0 and score!= 0:
        height -= 2
    return height

score = 0
height = 100
while True:
    height = levelUp(score, height)
    score+=1

调用
height=level\u up(高度,分数)
并相应地调整您的功能。您尝试了什么?这里有什么问题?每次你提到一个函数时,你能说明你在说什么函数吗?