Reputation: 488
I made a program in Idle that says:
for trial in range(3):
if input('Password:') == 'password':
break
else:
# didn't find password after 3 attempts
**I need a stop program here**
print ("Welcome in")
Remember, this is in Idle, so I need program for Idle, not CMD. I also am using Python 3.2, if that helps.
Upvotes: 1
Views: 4368
Reputation: 1
I tried sys.exit()
and it highlights 'sys'
as INVALID SYNTAX
.
It might be something to do with how I'm doing it, but if that's the case, then IDK then.
Upvotes: 0
Reputation: 250951
use sys.exit()
or raise SystemExit
import sys
for trial in range(3):
if input('Password:') == 'password':
break
else:
sys.exit()
print ("Welcome in"))
Edit:
To end it silently wrap it in a try-except
block:
try:
import sys
for trial in range(1):
if raw_input('Password:') == 'password':
break
else:
raise SystemExit #or just sys.exit()
print ("Welcome in")
except SystemExit:
pass #when the program throws SysExit do nothing here,i.e end silently
Upvotes: 2
Reputation: 134841
A much nicer way to do this IMHO would be to put your program into a function and return
when you want it to stop. Then just call the function to run your program.
def main():
for trial in range(3):
if input('Password:') == 'password':
break
else:
return
print ("Welcome in")
main()
Upvotes: 4
Reputation: 4232
I'm unsure what you mean by "in IDLE" vs "in CMD". A Python shell launched by IDLE should be able to be terminated the same way as a Python shell launched from the commandline.
Also, the tabs in your example appear to be wrong: everything below for...
and above print...
should be indented.
On to your question: are you asking for a command that terminates your script at that point? If so, adding the two lines from sys import exit
and then calling exit()
should do the trick, though it will raise a SystemExit
exception. If you don't like that, you can add a pass
handler for the SystemExit
exception type at the outer layer of your program.
Upvotes: 1