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程序中。有什么想法吗?是否与我可怕的代码有关?
非常感谢所有回复:)
答案 0 :(得分:4)
您需要使用raw_input()
代替input()
所以进行以下更改
def main()
...
op = raw_input ("Please enter the operation you wish to perform, +, -, *, / : ")
...
答案 1 :(得分:4)
假设您使用的是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
,因此您的程序运行正常并且不会显示您描述的行为。
答案 2 :(得分:3)
尝试在main()下编写
input("\n\nPress the enter key to exit: ")
现在它必须等你按Enter键才能再次输入并关闭,尝试一下,希望我帮助:)
答案 3 :(得分:2)
这与Windows处理执行的方式有关。默认是在程序终止后立即关闭。可能有一个设置可以解决此问题,但快速解决方案是向方向打开命令提示符cd
,并直接执行脚本。
答案 4 :(得分:0)
您的程序以递归方式调用main,因此最终会因堆栈过多而崩溃。这种轻微的变化就是你想要的。注意使用while循环和大写函数
import sys
import os
print ("Welcome to the Calculator")
def main():
while True:
a = int(input ("Please enter the first operand: "))
op = input ("Please enter the operation you wish to perform, +, -, *, / : ")
b = int(input ("Please enter the second operand: "))
if op == "+":
ans = (a + b)
elif op == "-":
ans = (a - b)
elif op == "*":
ans = (a * b)
elif op == "/":
ans = (a / b)
else:
print("Unknown operator!")
continue
print("Answer:", ans)
again = input("Would you like to perform another calculation? Y or N?")
if again.capitalize() == "N":
break
main()