Python程序出现NameError: name 'Roblox' is not defined错误求助
问题分析与解决
你的代码触发NameError的核心原因是缩进错误,Python依赖缩进划分代码块,错误的缩进会导致变量作用域解析异常。
错误根源
定义完全局变量后,print、input以及后续的if语句都被错误缩进,而最后的else没有和if保持同级缩进。这种混乱的缩进会让Python解析时,误以为if语句内的Roblox是未定义的局部变量,即便你在全局作用域已经定义了该变量。
修正后的代码
from sys import exit didlogcorrect = 1 Minecraft = 'Minecraft' Roblox = 'Roblox' Exit = 'Exit' chrome = 'chrome' print('Welcome To PotatOS') user_input = input("What would you like to do on PotatOS: ") if user_input == Roblox: print('Unable to connect to wifi Now terminating process') elif user_input == Exit: exit() elif user_input == chrome: print('You open Chrome Thinking What should i do now Maybe youtube idk, Then you close Chrome cause your bored!') elif user_input == Minecraft: print('Crashed, Reason 1, you close it cause your mad it crashed') else: print('PotatOS : BEEERGZ Unable to understand')
修正要点
- 移除
print、user_input及if语句前多余的缩进,让这些代码回到全局作用域 - 调整
else的缩进,使其和前面的if保持同级,确保语法结构完整
内容的提问来源于stack exchange,提问作者BryanThePotato
相关产品推荐
相关产品推荐

