Python IDLE与VS Code执行同代码结果不同的技术求助
问题排查:VS Code与Python IDLE运行同代码结果不一致
问题背景
两段环境均使用Python 3.10.10,运行以下代码时,IDLE执行符合预期,但VS Code报错。
原代码
while True: try: number = int(input("Enter the number: ")) except ValueError: print("Sorry, I didnt understand that.\n") #输入非整数时触发 continue if number < 623: print("Input should be more than or equal to 623.\n") #输入小于623的数时触发 continue elif number > 1920: print("Input should be less than or equal to 1920.\n") #输入大于1920的数时触发 continue else: break #输入符合要求的数时,循环终止
问题原因
代码中的比较运算符被写成了HTML转义字符<(对应<)和>(对应>),这属于Python语法错误:
- IDLE在处理代码时自动将这些转义字符解析成了正确的
<和>,因此能正常运行; - VS Code严格保留了代码中的转义字符,Python解释器无法识别,直接抛出语法错误。
修复方案
将代码中的<替换为<,>替换为>,修正后的代码如下:
while True: try: number = int(input("Enter the number: ")) except ValueError: print("Sorry, I didnt understand that.\n") #输入非整数时触发 continue if number < 623: print("Input should be more than or equal to 623.\n") #输入小于623的数时触发 continue elif number > 1920: print("Input should be less than or equal to 1920.\n") #输入大于1920的数时触发 continue else: break #输入符合要求的数时,循环终止
内容的提问来源于stack exchange,提问作者Inferno
相关产品推荐
相关产品推荐

