You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为何同一Python代码输出不同?4年前Python3教程代码疑问

两段Python代码输出不一致的问题

我照着4年前的Python 3 YouTube教程写代码,结果输出和讲师的不一样。下面这两段代码本该产生相同输出,但实际结果不同:

第一段代码

num = [5,2,5,2,2]

for x_counts in num:

    output = ''

    for count in range(x_counts):

        output += "x"

        print(output)

第二段代码

numbers = [5,2,5,2,2]

for x in numbers:

    print("x" * x)

问题原因

第一段代码的print(output)写在了内部的for循环里,每拼接一个"x"就会打印一次,所以对于列表里的每个数字n,会输出n行,每行依次是1个x、2个x……直到n个x。

而第二段代码的print("x" * x)在外部循环里,每个数字只对应打印一行n个x的字符串,这才是教程里应该得到的正确输出。

要让第一段代码和第二段输出一致,只需要把print(output)移到内部循环外面,修改后代码如下:

num = [5,2,5,2,2]

for x_counts in num:
    output = ''
    for count in range(x_counts):
        output += "x"
    print(output)

内容的提问来源于stack exchange,提问作者buny bravelike

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.08 02:55:55