为了账号安全,请及时绑定邮箱和手机立即绑定

我如何使用 while 循环和 Python 进行编码

我如何使用 while 循环和 Python 进行编码

DIEA 2023-08-08 09:57:59
创建一个程序,将 1、2、3... 中的所有数字相乘,并在乘积大于 1000 时结束。我尝试了这段代码,但它不起作用。produkt = 1while produkt<1000:    print(produkt)    produkt = produkt*(produkt +1)    if produkt < 1000:        break
查看完整描述

5 回答

?
翻阅古今

TA贡献1780条经验 获得超5个赞

produkt = 1

counter = 2

while produkt < 1000:

    print(produkt, end=" ")

    produkt = produkt * counter

    counter += 1

print(produkt)

1 2 6 24 120 720 5040


查看完整回答
反对 回复 2023-08-08
?
收到一只叮咚

TA贡献1821条经验 获得超4个赞

只是为了好玩。

>>> next(filter(1000 .__lt__, itertools.accumulate(itertools.count(1), operator.mul)))
5040


查看完整回答
反对 回复 2023-08-08
?
慕雪6442864

TA贡献1812条经验 获得超5个赞

我想你想要:


number = 1

produkt = number

while produkt<=1000:

    print(produkt)

    number += 1

    produkt = produkt * number

结果:


1

2

6

24

120

720



查看完整回答
反对 回复 2023-08-08
?
浮云间

TA贡献1829条经验 获得超4个赞

您需要 2 个变量,一个用于存储,total另一个用于存储index(1, 2, 3, ...)


index = 1

total = 1

while index < 1000:

    total *= index  # same as: total    = total * index

    index += 1  # same as: index = index +1

    # print(f'{index - 1} => {total}') uncomment if you want to follow the values


print(f"Stop at total {total}, index was {index}")

你会得到以下内容


1 => 1

2 => 2

3 => 6

4 => 24

5 => 120

6 => 720

7 => 5040

8 => 40320

9 => 362880

10 => 3628800

...

Stop at total 402...000, index was 1000


查看完整回答
反对 回复 2023-08-08
?
温温酱

TA贡献1752条经验 获得超4个赞

您可以按以下方式修改代码:变量produkt取值 1,2,3,...,它们的乘积存储在produkt_end.


produkt = 1

produkt_end = 1

while True:

    print(produkt_end)

    produkt_end = produkt_end*produkt

    produkt = produkt+1

    if produkt_end > 1000:

        break

它将显示produkt_end:


1

1

2

6

24

120

720


查看完整回答
反对 回复 2023-08-08
  • 5 回答
  • 0 关注
  • 95 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信