Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/image-processing/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 用户限制整数_Python_Python 3.x - Fatal编程技术网

Python 用户限制整数

Python 用户限制整数,python,python-3.x,Python,Python 3.x,如何从用户原始输入将整数输入缩小到特定长度,如“7”(每个示例): def number(): number=int(input("Number:")) print(number) number=1234567 如果len(number)7,则必须有一个while条件: print("Error") phone=int(input("Number:"))` 谢谢&圣诞快乐在您尝试转换为int之前,请检查长度: def number(): while True: i

如何从用户
原始输入将整数输入缩小到特定长度,如“7”(每个示例):

def number():
number=int(input("Number:"))
print(number)

number=1234567
如果len(number)<7或len(number)>7
,则必须有一个while条件:

print("Error")
phone=int(input("Number:"))` 

谢谢&圣诞快乐

在您尝试转换为int之前,请检查长度:

def number():
    while True:
        i = input("Number:") 
        if len(i) > 7:
            print("Number can only contain at most 7 digits!")
            continue
        try:
            return int(i)
        except ValueError:
            print("Invalid input")

如果您想要正好7,请使用
If len(i)!=7
并相应地调整错误消息。我还使用了try/except as,因为长度为7并不意味着它是一个有效的数字字符串。如果你想允许负子,你可以
如果len(i.lstrip(“-”)>7:

可能重复@AbhishekSingh,这是一个单独的特殊情况,我需要它是一个原始输入,并且只需要一个整数。@Phyti,原始输入是python2,你的资格证上有标签python3@PadraicCunningham对不起,我是说input@PadraicCunningham您的代码返回以下错误:TypeError:type'int'的对象没有len(),我必须说如果len(number)7:print(“输入无效”),并再次打印原始输入(int(“number”)。您根本不使用number,如果我检查长度,并且只有在长度可接受时才尝试强制转换为int,如果您最多需要7位数字,那么
如果len(i)>7:
将按照您的需要工作,因为任何长度>7都不会被忽略。请运行code@Phyti。。
while True
会一直重新编程,直到收到正确的输入…好的,我会@JoranBeasley