2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

for文で二重ループとついでにprint文の挙動

Last updated at Posted at 2013-10-16

ちらちら調べたりググったりしてると世にはCかC++のばかり出てきてアレなのでCで書かれたソースや解説も理解しなければという。

Cでの二重forループの例文の参考先さま
http://tokyo-ct.net/usr/kosaka/for_students/CIntro/loop/loop.html

for文.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文.py
# !/usr/bin/env python
import sys

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

はい、これでCで書かれたお手本のあんなこんなのも脳内で置き換えて読み放題に。
まぁ二重ループ理解するよりpythonでprint出力は自動で改行が付くのに苦労しました。
','で改行させないようにすると半角スペースでスカスカに。。。
改行させないようにすると sys.stdout.write('*') 以外の方法はちょっと見当たらなかったっぽい。
現時点では挙動の違いの把握と使い分けが出来ていればいいかな?と。。

ああ、、九九の表を練習してみたら表示で見える挙動は、"sys.stdout.write('\n')" と "print" のみの行は同等の挙動っぽい。

九九の表.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')

AOJで何度もprintのみで使う場面があったのはこういう挙動が必要な時だったのね。

Cの二重ループが脳内で置き換えの目的とは別に今回の意外な収穫はprintの挙動の違いが少し見えたこと。
もっと多重ループの場合やら

2
2
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?