From Import Statements: Ending A Program Early With Sys - Exit
From Import Statements: Ending A Program Early With Sys - Exit
We’ll learn
more about them later in the book.
from import Statements
An alternative form of the import statement is composed of the from keyword,
followed by the module name, the import keyword, and a star; for
example,
from random import *.
With this form of import statement, calls to functions in random will not
need the random. prefix. However, using the full name makes for more readable
code, so it is better to use the normal form of the import statement.
Ending a Program Early with sys.exit()
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.
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.
Summary
By using expressions that evaluate to True or False (also called conditions),
you can write programs that make decisions on what code to execute and
what code to skip. You can also execute code over and over again in a loop
while a certain condition evaluates to True. The break and continue statements
are useful if you need to exit a loop or jump back to the start.
These flow control statements will let you write much more intelligent
programs. There’s another type of flow control that you can achieve