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 win = 1: score += 1 elif lose: score -= 1
在第二个函数中使用“赢”和“输”时出错。你知道吗
不需要在函数外使用这个变量,因为它返回值。而是直接使用函数返回值:
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
或者更简单,无需使用变量win、lose和rand:
win
lose
rand
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,并在结尾处忘记它。也许您需要这样的方法从现有值计算新的分数并返回新结果:
scores
score
1
-1
def calc_score(score=0): if winOrLose(): return score += 1 else: return score -= 1
不需要在函数外使用这个变量,因为它返回值。而是直接使用函数返回值:
或者更简单,无需使用变量
win
、lose
和rand
:但还有一件事:在函数
scores
中如何处理变量score
?现在它什么也不做,只是将局部变量score
设置为1
或-1
,并在结尾处忘记它。也许您需要这样的方法从现有值计算新的分数并返回新结果:相关问题 更多 >
编程相关推荐