If you want to check for valid input, try
def z(n):
if -1 < n < 1000 : return ('000'+str(n))[-4:]
if -1 < n < 10000 : return '0'+str(n//10)
raise ValueError('n = %d is out of range (0 ≤ n < 10000).'%n)
The first if
catches all the n < 1000
numbers and returns the tail
of a a longer string.
The second if catches all the numbers in 999 < n < 10000
and uses
integer division (the //
operator) to remove the last digit.
The raise
statement is reached only if n
is outside the valid
interval, so we can raise an exception (ValueError
seems
appropriate), providing also an error message for the caller.
Having previously defined z(n)
in the interpreter we have
In [32]: z(4567)
Out[32]: '0456'
In [33]: z(567)
Out[33]: '0567'
In [34]: z(20000)
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-34-3a36d9b24c14> in <module>
----> 1 z(20000)
<ipython-input-26-d5602c2c4b24> in z(n)
2 if -1 < n < 1000 : return ('000'+str(n))[-4:]
3 if -1 < n < 10000 : return '0'+str(n//10)
----> 4 raise ValueError('n = %d is out of range (0 ≤ n < 10000).'%n)
ValueError: n = 20000 is out of range (0 ≤ n < 10000).
And eventually an example of how one can manage the exception in their code:
In [35]: for n in (-1, 0, 1, 999, 9999, 10000):
...: try:
...: print('%8d ——→'%n, z(n))
...: except ValueError as e:
...: print(e)
n = -1 is out of range (0 ≤ n < 10000).
0 ——→ 0000
1 ——→ 0001
999 ——→ 0999
9999 ——→ 0999
n = 10000 is out of range (0 ≤ n < 10000).
In [36]: