【发布时间】:2021-02-08 20:41:07
【问题描述】:
我创建了一个 while 循环,当其中的事物数量达到“计数”变量时,该循环需要停止,但我不太确定如何进行此操作。这是上下文的完整代码,但我遇到问题的部分在最后。此外,当用户输入错误时,代码会出现错误,这可能是我经过几次尝试后可以自己修复的问题,但我不确定如何解决。无论如何,这里的主要问题是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())
【问题讨论】:
-
这段代码根本不运行。它在
.index()告诉你它需要一个参数时失败 -
抱歉,我想我做了一些其他尝试,最终发送了错误版本的代码。一切都很好,人们给出了很好的答案
标签: python list loops while-loop sequence