用于测试python的倒计时函数

2024-10-01 13:24:19 发布

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

def test_countdown(self):
    from_3 = '3\n2\n1\nBlastoff!'
    self.assertEqual(countdown(3), from_3)
    from_0 = 'Blastoff!'
    self.assertEqual(countdown(0), from_0)
#THIS IS THE TEST
def countdown(n):
    while n>0:
        print(n)
        n=n-1
    print("Blastoff!")
#This is my code for the function

It is not passing the test because on the back end it is coming out as 'none' > for countdown(3) instead of '3\n2\n1\nBlastoff!'


Tags: thefromtestselfforisdefthis
1条回答
网友
1楼 · 发布于 2024-10-01 13:24:19

您正在打印,而不是连接:

def countdown(n):
    return '\n'.join(map(str, range(n, 0, -1))) + '\nBlastoff!'

或如Lalaland建议的:

def countdown(n):
    result = ''

    while n > 0:
        result += str(n) + '\n'
        n = n - 1 # decrement

    result = result + '\nBlastoff!'
    return result # not printing 

相关问题 更多 >