Here, we try to read the integer from the command line argument as a string at sys.argv[1]
. If none was supplied by the user, this attempt will raise an IndexError
(since sys.argv
would be a list containing only the program name at sys.argv[0]
); if the user supplied a command line argument but not one which can be cast to an integer, the line n = int(sys.argv[1])
will raise a ValueError
. We also raise our own ValueError
exception if the argument is an integer less than 1.
import sys
try:
n = int(sys.argv[1])
if n < 1:
raise ValueError
except (IndexError, ValueError):
print('Please enter an integer greater than 0 on the command line.\n'
'For example, python {:s} 8'.format(sys.argv[0]))
sys.exit(1)
while True:
print(n, end=' ')
if n == 1:
break
if n % 2:
n = 3 * n + 1
else:
n = n // 2
print()