Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

When the "while loop" is over, it writes "aaa" twice

Code:

n = 10
def test():
    global n
    
    while n > 0:
        n -= 1
        print(n)
        if n == 2:
            test()
    print("aaa")

test()

Output:

9
8
7
6
5
4
3
2
1
0
aaa
aaa

Why does it write "aaa" twice?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I need to use it in my another project but it writes it twice.

>Solution :

When you call test() in the if statement, that causes the function to print out the rest of the numbers and then "aaa".

Once it has done that, the program returns to the point at which test() was last called (in the if statement) so it carries on running and prints "aaa" again.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading