如何在另一个函数的不同函数中使用已定义的变量?

2024-09-28 17:29:03 发布

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

def winOrLose():
   rand = random.randint(0,1)
   if rand == 1:
      win = 1
      return win
   elif rand == 0:
      lose = 0
      return lose

def scores():
    score = 0
    if win = 1:
       score += 1
    elif lose:
       score -= 1

在第二个函数中使用“赢”和“输”时出错。你知道吗


Tags: 函数returnifdefrandomwinscorerandint
1条回答
网友
1楼 · 发布于 2024-09-28 17:29:03

不需要在函数外使用这个变量,因为它返回值。而是直接使用函数返回值:

def winOrLose():
   rand = random.randint(0,1)
   if rand == 1:
      win = 1
      return win
   elif rand == 0:
      lose = 0
      return lose

def scores():
    score = 0
    if winOrLose() == 1:
       score += 1
    else:
       score -= 1

或者更简单,无需使用变量winloserand

def winOrLose():
    if random.randint(0,1) == 1:
        return True
    else:
        return False

def scores():
    score = 0
    if winOrLose():
        score += 1
    else:
        score -= 1

但还有一件事:在函数scores中如何处理变量score?现在它什么也不做,只是将局部变量score设置为1-1,并在结尾处忘记它。也许您需要这样的方法从现有值计算新的分数并返回新结果:

def calc_score(score=0):
    if winOrLose():
        return score += 1
    else:
        return score -= 1

相关问题 更多 >