用自定义打印语句替换迭代输出

2024-06-14 11:43:44 发布

您现在位置:Python中文网/ 问答频道 /正文

def the(x):
    i = 0
    while i < 6:
        i += x
        print "i equals %s" % i
        if i == 5:
            print "This replaces the 5th iteration"

我有一个循环,它将I增加1,在I<;6处停止,并为每次迭代打印一个字符串。你知道吗

我想删除第5次迭代(“I等于5”)并用字符串替换它:“This replaces the 5th iteration”。你知道吗

我有什么选择?你知道吗


Tags: the字符串ltifdefthisprintreplaces
1条回答
网友
1楼 · 发布于 2024-06-14 11:43:44

使用else语句在打印前检查条件。在检查是否是第五个之前,你已经打印了第五个。(我在print中添加了括号,因为我使用的是python3,应该仍然可以在python2中使用)

def the(x):
    i = 0
    while i < 6:
        i += x
        if i == 5:
            print("This replaces the 5th iteration")
        else:
            print("i equals %s" % i)

>>> the(1)
i equals 1
i equals 2
i equals 3
i equals 4
This replaces the 5th iteration
i equals 6

相关问题 更多 >