Python函数内变量p外部未定义:原因及解决方法求助
问题原因与修复方案
原因
你在question1()和question2()里定义的p是函数局部变量,这类变量的作用域仅限于函数内部,函数执行结束后就会被销毁,外部的循环代码根本无法访问到它们,所以会出现p未定义的错误。
修复方法
推荐让每个问题函数返回对应的正确答案,这样外部调用函数时可以接收这个返回值,用来和用户输入做对比。同时顺便修复代码里的其他小问题:
修改后的完整代码
import random def question1(): print("What is the Capital of Bangladesh?") print("Your options are: 1)Dhaka 2)Cumilla 3)Rangpur 4)Barishal") # 返回正确答案 return 1 def question2(): print("Where is Bangladesh?") print("Your options are: 1)in Africa 2)in Asia 3)in Europe 4)in Antarctica") # 返回正确答案 return 2 n = 1 e = 5000 x = ["a", "b"] while n == 1: w = random.randint(0, 1) y = x[w] if "a" in y: correct_ans = question1() # 接收函数返回的正确答案 l = int(input("Type your option number:")) x.remove(y) if correct_ans == l: e *= 2 print(f"Congrats! You have won {e} points") # 用f-string拼接字符串和数字 else: print("You have lost!") print("You answered incorrectly!") n += 1 elif "b" in y: correct_ans = question2() # 接收函数返回的正确答案 l = int(input("Type your option number:")) x.remove(y) if correct_ans == l: e *= 2 print(f"Congrats! You have won {e} points") else: print("You have lost!") print("You answered incorrectly!") n += 1 print(f"Your total point is: {e}")
关键修改点
- 让
question1()和question2()通过return语句返回正确答案,外部用变量correct_ans接收 - 修复字符串与数字拼接的错误(原代码直接用
+连接字符串和整数会报错,改用f-string更简洁安全) - 修正拼写错误:
heve→have,Antertica→Antarctica,answers!改成更合理的incorrectly!
其他可选方案(不推荐)
如果非要用全局变量,可以在函数内部用global p声明,将p变成全局变量,但这种方式会让代码耦合度变高,不利于维护,所以不建议使用。示例如下:
def question1(): global p # 声明p为全局变量 print("What is the Capital of Bangladesh?") print("Your options are: 1)Dhaka 2)Cumilla 3)Rangpur 4)Barishal") p = 1
内容的提问来源于stack exchange,提问作者Rajesh Karmaker
相关产品推荐
相关产品推荐

