-->

Ending a Program Early with sys.exit() [Python]

The last flow control concept to cover is how to terminate the program. This always happens if the program execution reaches the bottom of the instructions. However, you can cause the program to terminate, or exit, by calling the sys.exit() function. Since this function is in the sys module, you have to import sys before your program can use it.
Ending a Program Early with sys.exit() [Python]
Ending a Program Early with sys.exit() [Python]


Open a new file editor window and enter the following code, saving it as exitExample.py:

import sys
while True:
print('Type exit to exit.')
response = input()
if response == 'exit':
sys.exit()
print('You typed ' + response + '.')


Run this program in IDLE. This program has an infinite loop with no
break statement inside. The only way this program will end is if the user enters
exit, causing sys.exit() to be called. When response is equal to exit, the program
ends. Since the response variable is set by the input() function, the user

must enter exit in order to stop the program.

0 Response to "Ending a Program Early with sys.exit() [Python]"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel