简体   繁体   English

Python 3限制基数10输入值

[英]Python 3 Limit base 10 input value

I am new to Python so not sure how best to structure this. 我是Python的新手,所以不确定如何最好地构建它。

I have a user inputing a number stored as B. 我有一个用户输入存储为B的号码。

The number can only be between 0-7. 该数字只能在0-7之间。

If the user enters 8 we print an error message. 如果用户输入8,我们将打印错误消息。

Sorry for the simplistic nature of the questio? 对不起问题的简单性质?

Thank you 谢谢

You can input any base number up to base 36: 您可以输入任何基数到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). 不断要求用户输入,直到一个有效的答案给出( break退出while True循环)。 ValueError is handled by the try since it can be raised if user gives something like 1.2 or hello . ValueErrortry处理,因为如果用户提供类似1.2hello ,则可以引发它。 Note that input() assigns a string to user_answer . 请注意, input()user_answer分配一个字符串。

(I am assuming you want an int not a float .) (我假设你想要一个int而不是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))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM