【问题标题】:How to use a while loop to print every number in a range in Python如何使用while循环打印Python范围内的每个数字
【发布时间】:2021-11-29 19:09:44
【问题描述】:

我正在处理一个练习题,它说:“创建一个函数,它接收一个整数作为参数(步骤)并打印从 0 到 100(包括在内)的数字,但在每个数字之间留下步骤。 两个版本:for 循环和 while 循环。

我可以使用 foo 循环来做到这一点:

def function(x):
    count = 0
    for x in range(0, 100, x):
        print(x)

我似乎无法让它与 while 循环一起工作。我试过这个:

def function(x):
    count = 0
    while count <= 100:
        count += x
        print(count)

所以请帮忙。谢谢!

【问题讨论】:

  • 打印后移动 count+=x
  • while版本中,在增加步长之前应该先打印。另外,for 版本中不需要count = 0
  • 真的!谢谢!

标签: python loops while-loop


【解决方案1】:

您需要在打印后增加count

def function(x):
    count = 1
    while count <= 100:
        print(count)
        count += x

【讨论】:

  • 使用count = 0 完成。谢谢!
猜你喜欢
  • 2019-08-18
  • 2018-09-15
  • 1970-01-01
  • 1970-01-01
  • 2020-04-17
  • 2021-03-06
  • 2013-02-25
  • 2022-12-20
  • 1970-01-01
相关资源
最近更新 更多