Skip to main content
 首页 » 编程设计

Python-通过CMD执行程序时,它只是在第二次输入后关闭

2025年05月04日11xxx_UU

import sys 
import os 
print ("Welcome to the Calculator") 
 
def main(): 
    a = input ("Please enter the first operand: ") 
    op = input ("Please enter the operation you wish to perform, +, -, *, / : ") 
    b = input ("Please enter the second operand: ") 
 
    a = int(a) 
    b = int(b) 
 
    if op == "+": 
            ans = (a + b) 
 
            print (ans) 
 
    elif op == "-": 
            ans = (a - b) 
            print (ans) 
 
    if op == "*": 
            ans = (a * b) 
            print (ans) 
 
    elif op == "/": 
            ans = (a / b) 
            print (ans) 
 
    again = input("Would you like to perform another calculation? Y or N?") 
 
    if again == "Y": 
            main() 
 
main() 

您好,很抱歉问了这么多问题。

基本上,我将我的代码放在上面,并通过双击 .py 文件执行代码,在提示消息后从 CMD 启动它:“请输入您要执行的操作,+,- , *,/:"

CMD 只是随机关闭自己。它也发生在我所有的 Python 程序中。任何想法为什么?是不是跟我的代码太烂有关?

非常感谢所有回复:)

请您参考如下方法:

假设您使用的是 python 2,而不是 3.3

问题是 python2 中的input 函数执行 代码。这意味着当用户输入 *、+、/、- 之一时,会引发异常(因为+ 或 - 或 * 或 / 不是完整的表达式或语句)并且程序终止,因此CMD 关闭。

要检查这一点,请尝试将 input 调用包装在 try...except 语句中:

try: 
    op = input('... * / - +') 
except Exception: 
    input('OPS!')   #just to verify that this is the case. 

特别是当我尝试在 python2 中键入 + 作为输入时得到的结果:

>>> input('') 
+ 
Traceback (most recent call last): 
  File "<stdin>", line 1, in <module> 
  File "<string>", line 1 
    + 
    ^ 
SyntaxError: unexpected EOF while parsing 

在 python2 中,您应该使用 raw_input 函数,它返回一个字符串。在 python3 中,raw_input 被重命名为 input,因此您的程序运行良好,不会显示您描述的行为。