P4.4.1: Hailstone sequence generator with a usage message
Question P4.4.1
Modify the Hailstone sequence generator of Exercise P2.5.7 to generate the hailstone sequence starting at any positive integer, $n$, that the user provides on the command line (use sys.argv). Handle the case where the user forgets to provide $n$ or provides an invalid value for $n$ gracefully.
Solution P4.4.1
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(f'Please enter an integer greater than 0 on the command line.\n'
f'For example, python {sys.argv[0]} 8')
sys.exit(1)
while True:
print(n, end=' ')
if n == 1:
break
if n % 2:
n = 3 * n + 1
else:
n = n // 2
print()