使用函数实现问答游戏时全局points变量无法更新,输出始终为0
问题原因及解决方案
原因
Python里整数是不可变类型,当你把points传入qea函数时,函数内部的z只是points的一个独立副本。修改z +=1只会改变这个局部副本的值,完全不会影响外部的points变量,所以最终输出的points始终是初始值0。
修复方法
这里提供三种可行的修复方式:
方法1:让函数返回更新后的分数
通过函数返回修改后的分数,再赋值给外部的points变量:
def qea(x, y, z): if x == y: print("Correct!") z += 1 else: print('Wrong!') return z points = 0 # 第一题 question1 = input("Who is the president of USA?: ").upper() answer1 = "JOE BIDEN" points = qea(question1, answer1, points) # 第二题(注意变量名不要重复) question2 = input("Alexander...: ").upper() answer2 = "THE GREAT" points = qea(question2, answer2, points) print(points)
方法2:使用可变对象传递分数
用列表这类可变对象存储分数,函数内部修改列表元素会直接影响外部:
def qea(x, y, z): if x == y: print("Correct!") z[0] += 1 else: print('Wrong!') points = [0] question1 = input("Who is the president of USA?: ").upper() answer1 = "JOE BIDEN" qea(question1, answer1, points) question2 = input("Alexander...: ").upper() answer2 = "THE GREAT" qea(question2, answer2, points) print(points[0])
方法3:使用全局变量
在函数内部用global关键字声明使用外部的points变量:
def qea(x, y): global points if x == y: print("Correct!") points += 1 else: print('Wrong!') points = 0 question1 = input("Who is the president of USA?: ").upper() answer1 = "JOE BIDEN" qea(question1, answer1) question2 = input("Alexander...: ").upper() answer2 = "THE GREAT" qea(question2, answer2) print(points)
内容的提问来源于stack exchange,提问作者Astrologo
相关产品推荐
相关产品推荐

