Python3.13交互式环境输入执行命令触发第1行SyntaxError,求助
问题分析与解决
核心错误原因
你遇到的语法错误和代码本身无关——你错误地在Python交互式解释器(>>>)里输入了系统命令行的执行指令。错误信息里的第一行& C:/Users/user1/...是Windows命令提示符的执行命令,不属于Python代码范畴,所以解释器会抛出语法错误。
正确运行方式
方式1:通过系统命令行运行脚本(推荐)
- 打开Windows命令提示符(CMD)
- 切换到脚本所在的桌面目录:
cd c:/Users/user1/Desktop - 直接执行脚本文件:
注意不要加开头的python "homework 2.py"&符号,这是多余的系统命令前缀。
方式2:在Python交互式环境中运行代码
如果要在>>>环境里运行,有两种选择:
- 逐行输入你的计算器代码(跳过那行带
&的错误命令) - 直接加载执行脚本文件:
exec(open("c:/Users/user1/Desktop/homework 2.py").read())
代码优化建议(可选)
你的代码本身可以正常运行,但有两个小细节可以优化:
- 目前用
//是整数除法,若需要保留小数的浮点数除法,改成D = nb1 / nb2 - 如果用户输入非整数内容(比如字母),代码会报错,可以添加简单的异常处理:
print("Welcome to my Calculator!!") try: nb1 = int(input("Enter the 1st number: ")) nb2 = int(input("Enter the 2nd number: ")) A = nb1 + nb2 S = nb1 - nb2 M = nb1 * nb2 D = nb1 / nb2 # 改用浮点数除法 print(f"The addition of {nb1} + {nb2} is: {A}") print(f"The subtraction of {nb1} - {nb2} is: {S}") print(f"The multiplication of {nb1} x {nb2} is: {M}") print(f"The division of {nb1} / {nb2} is: {D}") except ValueError: print("请输入有效的整数!") except ZeroDivisionError: print("除数不能为0!")
内容的提问来源于stack exchange,提问作者hamoudio
相关产品推荐
相关产品推荐

