我的作业有些问题。关于停止循环

时间:2019-09-09 18:13:08

标签: python for-loop while-loop break

我正在做作业。而且我找不到解决方法。

我曾尝试使用for语句下的中断,但没有任何回报。 问题是“完成以下程序,以便当找到大于1000且能被33和273整除的最小正整数时,循环停止。”

这是我尝试执行的代码

n = 1001 #This one is required

while True: #This one too
    for i in range(n,___): # I don't know what should i put in the blank
          if i%33 == 0 and i%273 == 0: # I really confused about this line
              break # Should i break it now?, or in the other lines?
print(f"The value of n is {n}") #This one is also required

我不知道我应该在哪些行中打断(或者我不必使用它?),或者我应该创建一个调用列表最小数量的函数?

我很抱歉我的语言以及我的编程技巧多么愚蠢 我会接受所有评论。谢谢

4 个答案:

答案 0 :(得分:4)

您已经有一个while True:循环,不需要内部for循环来搜索您的电话号码,只需在n循环中不断增加while添加新计数器后,找到所需的数字后,无限while True:循环将停止(使用break),因此将执行打印语句:

n = 1001  #  start at 1001

while True:  #  start infinite loop
    if n % 33 == 0 and n % 273 == 0:  #  if `n` found
        break  #  exit the loop
    n += 1  #  else, increment `n` and repeat

print(f"The value of n is {n}")  #  done, print the result

输出:

The value of n is 3003

答案 1 :(得分:2)

感谢您说这是作业!不仅可以给出答案,而且可以更详细地解释事情。

有几件事需要解释:

1)n%33是n除以33的余数。因此66%33为0,67%33为1。

2)For循环通常是当您需要在定义的范围(并非总是,但通常是)上循环时。例如。 “将前100个整数相加”。 while循环在这里更有意义。它肯定会终止,因为在某个时候您将达到33 * 237。

3)如果i%33 == 0和i%237 == 0:表示当数字可以均分(无余数)为37和237时,我们想做些什么。

n=1001
while True:
    if n%33==0 and n%237==0:
        print(n)
        break
    n+=1

答案 2 :(得分:1)

for循环在这里无济于事,因为您不知道何时结束循环。通常,当您要遍历的事物范围已知时,可以使用for循环。

相反,请执行以下操作:

在开始while: True循环之前:将i设置为0,

然后将i每次循环增加1。

此外,别忘了在i>1000时停止循环!

答案 3 :(得分:1)

嗯,只要上限至少与最大可能结果一样高,您仍然可以使用for循环。结果将在i中,而不是n中,并且for循环就足够了,而不是附加的while循环。当{33}和237的余数均为零(即它们都是因数)时,for循环将中断。

n = 1001 #This one is required

for i in range(n, 33 * 237 + 1): # I don't know what should i put in the blank
    if i % 33 == 0 and i % 237 == 0: # I really confused about this line
        break #
print(f"The value of i is {i}") #This one is also required

您还可以使用while循环,并对条件使用相同的逻辑。在这种情况下,我们测试至少不是一个因素,然后继续循环,直到33和237被i均分。

n = 1001 #This one is required

i = n
while i % 33 or i % 237:
    i += 1
print(f"The value of i is {i}") 
相关问题