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

创建一个程序,将 1、2、3... 中的所有数字相乘,并在乘积大于 1000 时结束。


我尝试了这段代码,但它不起作用。


produkt = 1

while produkt<1000:

    print(produkt)

    produkt = produkt*(produkt +1)

    if produkt < 1000:

        break


DIEA
浏览 98回答 5
5回答

翻阅古今

produkt = 1counter = 2while produkt < 1000:&nbsp; &nbsp; print(produkt, end=" ")&nbsp; &nbsp; produkt = produkt * counter&nbsp; &nbsp; counter += 1print(produkt)1 2 6 24 120 720 5040

收到一只叮咚

只是为了好玩。>>>&nbsp;next(filter(1000&nbsp;.__lt__,&nbsp;itertools.accumulate(itertools.count(1),&nbsp;operator.mul))) 5040

慕雪6442864

我想你想要:number = 1produkt = numberwhile produkt<=1000:&nbsp; &nbsp; print(produkt)&nbsp; &nbsp; number += 1&nbsp; &nbsp; produkt = produkt * number结果:12624120720

浮云间

您需要 2 个变量,一个用于存储,total另一个用于存储index(1, 2, 3, ...)index = 1total = 1while index < 1000:&nbsp; &nbsp; total *= index&nbsp; # same as: total&nbsp; &nbsp; = total * index&nbsp; &nbsp; index += 1&nbsp; # same as: index = index +1&nbsp; &nbsp; # print(f'{index - 1} => {total}') uncomment if you want to follow the valuesprint(f"Stop at total {total}, index was {index}")你会得到以下内容1 => 12 => 23 => 64 => 245 => 1206 => 7207 => 50408 => 403209 => 36288010 => 3628800...Stop at total 402...000, index was 1000

温温酱

您可以按以下方式修改代码:变量produkt取值 1,2,3,...,它们的乘积存储在produkt_end.produkt = 1produkt_end = 1while True:&nbsp; &nbsp; print(produkt_end)&nbsp; &nbsp; produkt_end = produkt_end*produkt&nbsp; &nbsp; produkt = produkt+1&nbsp; &nbsp; if produkt_end > 1000:&nbsp; &nbsp; &nbsp; &nbsp; break它将显示produkt_end:112624120720
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python