Reputation: 337
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()
Hi, sorry for asking so many questions.
Basically, I put my code above, and upon executing the code by double clicking the .py file, which launches it off CMD, after being prompted with the message: "Please enter the operation you wish to perform, +, -, *, / :"
CMD just randomly closes itself. It's also happened to all my Python programs. Any ideas why? Is it to do with my terrible code?
All replies are much appreciated :)
Upvotes: 1
Views: 1437
Reputation: 77007
You need to use raw_input()
instead of input()
So make the following change
def main()
...
op = raw_input ("Please enter the operation you wish to perform, +, -, *, / : ")
...
Upvotes: 4
Reputation: 101989
Assuming you are using python 2, and not 3.3
The problem is that the input
function in python2 executes code. this means that when the user enters one of *
, +
, /
, -
an exception is raised(since +
, or -
or *
or /
aren't complete expressions or statements) and the program terminates, hence the CMD closes.
To check this try to wrap the input
call in a try...except
statement:
try:
op = input('... * / - +')
except Exception:
input('OPS!') #just to verify that this is the case.
In particular this is what I get when trying to type +
as input in python2:
>>> input('')
+
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<string>", line 1
+
^
SyntaxError: unexpected EOF while parsing
In python2 you should use the raw_input
function, which returns a string. In python3 raw_input
was renamed to input
, and thus your program runs fine and doesn't show the behaviour you describe.
Upvotes: 4
Reputation: 982
Try, under main(), write
input("\n\nPress the enter key to exit: ")
now it would have to wait for you to press enter so it passes bye that input and closes, try that, hope i helped :)
Upvotes: 3
Reputation: 1614
This has to do with how Windows handles the execution. The default is to close right away after the program has terminated. There may be a setting to fix this, but a quick solution is to open up Command Prompt, cd
to the direction, and execute your script directly.
Upvotes: 2