我的 while true 循环应该在休息时计数到 100,但它不起作用

问题描述 投票:0回答:1

我应该创建一个 while true 循环。该程序应该数到 100,并打印每个数字。然而,程序必须打印一个句子,而不是计算 3、5 和 3 和 5 的倍数。打印数字 100 后循环应该存在。但我的程序根本没有运行。

我希望我的程序能够打印 1-100 之间的每个数字,但对于 3、5 和 3 和 5 的倍数,它应该打印不同的句子。例如:3 的倍数打印 x,5 的倍数打印 y,3 和 5 的倍数打印 xy。应该会突破100 这是我目前编写的代码:

count = 1
while True:
  if count % 3 == 0 and count % 5             == 0:
     print("hello there, you gorgeous")
     count = count + 1
     continue
  if count % 3 == 0:
     print("hello world")
     count = count + 1
     continue
  if count % 5 == 0:
     print("love yourself")
     count = count + 1
     continue
  if count > 100:
     break
     print(count)
     count = count + 1
loops while-loop spyder python-3.8
1个回答
0
投票

有几个问题:

  • 程序以

    count
    为 1 开始,这意味着
    if
    条件都不为真。在这种情况下,
    count
    不会增加,因此循环将以与之前相同的状态重复,从而导致无限循环。当所有条件都不成立时,您也应该增加
    count
    。该错误可能是由最后两条语句(位于
    break
    之后)的缩进错误引起的。这些应该无条件执行并且不缩进。

  • 说明说您应该打印每个数字,但您的代码没有这样做:即使在修复了缩进问题之后,

    continue
    语句也会使
    print
    调用被跳过。这个问题可以通过将
    print
    放在循环体的顶部来解决。

  • 应该always测试退出条件,不仅在最终情况下,而且在打印短语时也是如此。因此,最好将此测试移至循环体的顶部。

这是您的代码,经过最少的修改。评论指出了上述几点的更正之处:

count = 1
while True:
  if count > 100:  # this condition must be tested in each iteration
     break
  print(count)   # Always print the number
  if count % 3 == 0 and count % 5 == 0:
     print("hello there, you gorgeous")
     count = count + 1
     continue
  if count % 3 == 0:
     print("hello world")
     count = count + 1
     continue
  if count % 5 == 0:
     print("love yourself")
     count = count + 1
     continue
  count = count + 1  # indentation issue solved

这解决了问题,但有一些代码重复:

  • count = count + 1
    :为了避免这种重复,请不要在此处使用
    continue
    ,而使用
    elif
    语句来代替——这样可以避免执行进入多个条件块。
  • count % 3 == 0
    :要避免这种重复,请使用嵌套
    if

其次,最好将短语 next 打印在它们所适用的数字后面,而不是在它们下面。您可以将

end
参数与
print
调用一起使用:

没问题,但是先缩进2个空格,然后缩进3个空格,不一致。一个常见的习惯是始终使用 4 个空格。

count = 1
while True:
    if count > 100:
        break
    print(count, end=" ")   # print phrase on the same line as number
    # use if-elif to avoid duplication
    if count % 15 == 0:  # avoid two modulo operations here
        print("hello there, you gorgeous")
    elif count % 3 == 0:
        print("hello world")
    elif count % 5 == 0:
        print("love yourself")
    else:
        print()
    count = count + 1

最后,虽然我知道您被要求使用

while True
,但这不是这种情况下的正确做法。这是基于
range
的循环的理想候选者:

for count in range(1, 101):
    print(count, end=" ")   # print phrase on the same line as number
    # use if-elif to avoid duplication
    if count % 15 == 0:  # avoid two modulo operations here
        print("hello there, you gorgeous")
    elif count % 3 == 0:
        print("hello world")
    elif count % 5 == 0:
        print("love yourself")
    else:
        print()
    count = count + 1
© www.soinside.com 2019 - 2024. All rights reserved.