[PYTHON] Double loop in for statement and then print statement behavior

If you look around or google, you will find only C or C ++ in the world, so you have to understand the source and explanation written in C.

References for double for loop example sentences in C http://tokyo-ct.net/usr/kosaka/for_students/CIntro/loop/loop.html

for statement.c


#include <stdio.h>

int main()
{
    int i,j;
    for (i=0;i<5;i++) {
        for (j=0;j<10;j++) {
            printf("*");
        }
        printf("\n");
    }
    return 0;
}

for statement.py


#!/usr/bin/env python
import sys

 for x in range(5):
     for y in range(10):
         sys.stdout.write('*')
     sys.stdout.write('\n')

Yes, with this, you can replace such a model written in C in your brain and read it as much as you want. Well, rather than understanding double loops, I had a hard time with python to automatically add line breaks to print output. If you do not break the line with',', it will be empty with a half-width space. .. .. It seems that I couldn't find any method other than sys.stdout.write ('*') if I tried not to break the line. At this point, should I be able to grasp the difference in behavior and use it properly? When. ..

Ah, when I practice the multiplication table, the behavior that I see on the display seems to be the same behavior for the lines with only "sys.stdout.write ('\ n')" and "print".

Multiplication table.py


#!/usr/bin/env python
import sys

for x in range(1,10):
  for y in range(1,10):
    print "{0:02d}".format(x*y),
# print
  sys.stdout.write('\n')

It was when this kind of behavior was necessary that AOJ used it only for print many times.

Apart from the purpose of replacing the double loop of C in the brain, this unexpected harvest showed a slight difference in the behavior of print. In the case of more multiple loops

Recommended Posts

Double loop in for statement and then print statement behavior
Loop the For statement in reverse in an HTML file on Django
Don't print and import logging for logging
Change the list in a for statement
Don't use readlines () in your Python for statement!