0

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

jamylak
  • 128,818
  • 30
  • 231
  • 230
Jeremy
  • 111
  • 1
  • 5
  • 11
  • _"B can only have an input from 0 -7 the result on b"_. You lost me at "the result on b". Is `b` a different variable from `B`? – Kevin Mar 04 '15 at 18:03
  • Are you getting these values from the user? Maybe you want [Asking the user for input until they give a valid response](http://stackoverflow.com/q/23294658/953482). You could have `number >=0 and number <= 7` for your validity condition. – Kevin Mar 04 '15 at 18:05
  • sorry using an iPhone no B and b are the same. I should say the result of b is then added to a so that a starts at 8 – Jeremy Mar 04 '15 at 18:05
  • 1
    Ok, I think I understand that part, then. But it's hard to answer your question because you didn't actually ask a question :-) – Kevin Mar 04 '15 at 18:14
  • This question feels unclear. Please edit it appropriately, so that we can answer. – user Mar 04 '15 at 18:17
  • I want to limit the user input. I.E user can input 0-7 but not 8 + – Jeremy Mar 04 '15 at 18:18
  • Updated answer sorry. I am new and trying to find the best way to explain what I am looking todo. Thank you all for your help. – Jeremy Mar 04 '15 at 18:23

2 Answers2

0

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.
motoku
  • 1,571
  • 1
  • 21
  • 49
0

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))
user
  • 5,370
  • 8
  • 47
  • 75