Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.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

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/ssl/3.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 如何将range()与while循环一起使用?_Python_List_While Loop_Range_Maxlength - Fatal编程技术网

Python 如何将range()与while循环一起使用?

Python 如何将range()与while循环一起使用?,python,list,while-loop,range,maxlength,Python,List,While Loop,Range,Maxlength,我需要创建一个空列表 向用户询问任何输入5次 仅当输入不存在时才将其添加到列表中 我不断地进入一个无限循环,而不是仅仅5次 这是我的密码: MyList = [] maxLengthList = range(5) while len(MyList) < maxLengthList: i = input("Enter a number to the list: ") if i not in MyList: MyList.append(i)

我需要创建一个空列表 向用户询问任何输入5次 仅当输入不存在时才将其添加到列表中

我不断地进入一个无限循环,而不是仅仅5次

这是我的密码:

MyList = []
maxLengthList = range(5)
while len(MyList) < maxLengthList:
    i = input("Enter a number to the list: ")
    if i not in MyList:
        MyList.append(i)
print("That's your numbers list")
print(MyList)

尝试学习for循环。您可以这样使用它们:对于范围5中的uu:。将它们用于可订阅格式。更多信息。

正确使用范围是:

for x in range(start, end):
    print(x)
因此,在您的情况下,它将是:

# Using underscore here since you do not need the value for each loop
for _ in range(5):
    i = input("Enter a number to the list: ")
    if i not in MyList:
        MyList.append(i)

但是,您可以将maxLengthList设置为5,而不是range5

您已将range函数用作最大长度的常量,这是不可能的 range5=range0,5它不会给您一个常数来使用 您无法将lenMyList与maxlengthlist进行比较 TypeMylist=int
TypeMaxLengthlist=range类在Python中,range是一个类似于生成器的不可变iterable对象。当你说range5时,它产生从0到4的数字。您可以使用for_循环在一个范围内迭代,而不是while_循环

出于您的目的,您根本不需要范围。没有它,您的代码可以完美地工作

MyList = []
maxLengthList = 5
while len(MyList) < maxLengthList:
    i = input("Enter a number to the list: ")
    if i not in MyList:
        MyList.append(i)
print("That's your numbers list")
print(MyList)

你为什么要用靶场?在lenMyList的时候做就行了5@flakes我照你说的做了,但循环了5次以上。非常感谢你的帮助和解释:没问题。确保你接受最适合你的答案。这里是这样做的程序和礼仪:谢谢你,我一定会学习更多的循环。