Python函数内缩进代码不执行,全局列表myList赋值失效问题求助
问题原因
1. Code1不执行的原因
Code1行首带有Python注释标记#,属于注释内容,默认不会被解释器执行,删掉行首的#即可启用这行代码。
2. Code2看起来没执行的原因
这行代码实际已经执行了,只是你没有遵守Python全局变量的修改规则:
如果需要在函数内部修改全局变量的值,必须先用global关键字声明该变量为全局变量,否则Python会将函数内的myList=['','','','','','','','','',]识别为创建了一个和全局变量同名的局部变量,修改只会作用在局部变量上,不会影响外部的全局myList,因此看起来就像这行代码没生效一样。
修正方案
只需要在函数开头新增global myList声明即可,另外Code1和Code2的逻辑完全重复,保留一处就行,参考修正后代码:
myList=['','','','','','','','','',] def continueGame(): # 声明本函数用到的myList是全局变量 global myList optionList1=['Yes', 'Y','y','yes','YES'] optionList2=['No','no','n','NO'] userChoice = '' while userChoice not in optionList1 and userChoice not in optionList2: userChoice = input("Want to continue the game ? (Y,N) :") if(userChoice not in optionList1 and userChoice not in optionList2): print("This is not the correct option. Please enter either Y or N.") userChoice = '' if userChoice in optionList1: # 直接在这里重置myList,不需要后面额外判断options myList=['','','','','','','','','',] return True else: return False
内容的提问来源于stack exchange,提问作者pc_fuel
相关产品推荐
相关产品推荐

