Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/335.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 当达到某个索引值时,如何停止向列表中添加数字的while循环?_Python_List_Loops_While Loop_Sequence - Fatal编程技术网

Python 当达到某个索引值时,如何停止向列表中添加数字的while循环?

Python 当达到某个索引值时,如何停止向列表中添加数字的while循环?,python,list,loops,while-loop,sequence,Python,List,Loops,While Loop,Sequence,我做了一个while循环,当循环中的东西的数量达到“count”变量时需要停止,但我不太确定如何进行。下面是上下文的完整代码,但我遇到的问题是在最后。此外,当用户输入错误时,代码会出错,这可能是我可以在几次尝试后自行修复的,但我不确定如何修复。无论如何,这里的主要问题是while循环。提前谢谢你的帮助 count = int(input("How many numbers should the sequence have? ")) question = input("

我做了一个while循环,当循环中的东西的数量达到“count”变量时需要停止,但我不太确定如何进行。下面是上下文的完整代码,但我遇到的问题是在最后。此外,当用户输入错误时,代码会出错,这可能是我可以在几次尝试后自行修复的,但我不确定如何修复。无论如何,这里的主要问题是while循环。提前谢谢你的帮助

count = int(input("How many numbers should the sequence have? "))
question = input("AP or GP? ")

# Asking the user for input on how many numbers the sequence will have
if question == "AP":
    APdiff = int(input("Insert the common difference for the AP: "))
    while type(APdiff) != int:
        print("Insert a valid input.")
        APdiff = int(input("Insert the common difference for the AP: "))
elif question == "GP":
    GPdiff = int(input("Insert the common ratio for the GP: "))
    while type(GPdiff) != int:
        print("Insert a valid input.")
        GPdiff = int(input("Insert the common ratio for the GP: "))
while question != "AP" and question != "GP":
    print("Please enter a valid input.")
    question = input("AP or GP? ")


def sequence_generator():


    #Setting up the sequences
    sequence = []
    number = 1

    #Defining the AP
    if question == "AP":
        while number in range(1, 99999999999999999999999999999999):
            sequence.append(number)
            number += APdiff
            if sequence.index() == count:
                break
    #Defining the GP
    elif question == "GP":
        while number in range(1, 99999999999999999999999999999999):
            sequence.append(number)
            number *= GPdiff
            if sequence.index() == count:
                break
    return sequence



print(sequence_generator())

您可以使用
while len(sequence)while循环在满足条件语句之前不会中断。例如:

x = 0
while (x < 5):
  print(x)
  x += 1
print('All done')
程序将执行代码块,直到满足条件,然后中断循环,不打印5。


要在while循环中断时执行操作,只需将代码放在while块之后。

此代码根本不运行。它在
.index()
告诉您它需要一个参数时失败。哦,很抱歉,我想我做了一些其他尝试,结果发送了错误版本的代码。尽管如此,人们给出了很好的回答,而循环也会按照OP的意图用
break
语句中断。请自己尝试,将
break
放在
i+=1
之后。由于迭代次数是预先知道的,我仍然更喜欢
for
循环。
x = 0
while (x < 5):
  print(x)
  x += 1
print('All done')
0
1
2
3
4
All done