I am new to Python so not sure how best to structure this.
I have a user inputing a number stored as B.
The number can only be between 0-7.
If the user enters 8 we print an error message.
Sorry for the simplistic nature of the questio?
Thank you
I am new to Python so not sure how best to structure this.
I have a user inputing a number stored as B.
The number can only be between 0-7.
If the user enters 8 we print an error message.
Sorry for the simplistic nature of the questio?
Thank you
You can input any base number up to base 36:
int(number, base)
Example:
>>> int("AZ14", 36)
511960
If you are talking about limiting the range of a base ten number, here's an example of that:
>>> the_clamps = lambda n, i, j: i if n < i else j if n > j else n
>>> for n in range(0, 10): print((the_clamps(n, 4, 8)))
...
4
4
4
4
4
5
6
7
8
8
>>>
Amendment:
To generate and handle errors:
>>> def mayhem(n, i, j):
... if n < i or n > j: raise Exception("Out of bounds: %i." % n)
... else: return n
...
>>> for n in range(10):
... try: print((mayhem(n, 4, 8)))
... except Exception as e: print((e))
...
Out of bounds: 0.
Out of bounds: 1.
Out of bounds: 2.
Out of bounds: 3.
4
5
6
7
8
Out of bounds: 9.
Constantly asks user for input, until a valid answer is given (break exits while True loop). ValueError is handled by the try since it can be raised if user gives something like 1.2 or hello. Note that input() assigns a string to user_answer.
(I am assuming you want an int not a float.)
user_answer = None
while True:
user_answer = input('Give a num from 0 to 7')
try:
if 0 <= int(user_answer) <=7:
break
else:
print('Out of range.')
continue
except ValueError:
print('Invalid answer, try again.')
print('Given number: {}'.format(user_answer))