LoginSignup
0
0

More than 1 year has passed since last update.

【pythonメモ】回数指定のfor文(for .. in range)の使い方

Last updated at Posted at 2022-01-29

1.はじめに

様々なプログラミング言語で使われるforループ。
pythonでは回数指定のforが3種類ある。
今更だけど、どうにも使いずらいので自分用のメモとしてまとめてみた。

2.実行環境

OS:windows10
Python 3.8.10(jupyter notebook上で実行)
PHPはpaiza.ioで実行

3.for .. in range

パターン1)for 繰り返し変数 in range(N1)

N1:指定回数
指定回数だけある処理を実行したい場合使える。

for i in range(5):
  print("Loto6")
出力結果
Loto6
Loto6
Loto6
Loto6
Loto6

ただし繰り返し変数も利用したい場合は、その値は0~N1-1となることに注意が必要になる。

for i in range (5):
  print("Loto6トライ:"+str(i)+"回目")
出力結果
Loto6トライ:0回目
Loto6トライ:1回目
Loto6トライ:2回目
Loto6トライ:3回目
Loto6トライ:4回目

パターン2)for 繰り返し変数 in range(N1,N2)

開始値を0以外にしたいときに使う。
N1:開始値,N2:終了値
ここでは、繰り返し変数はN1~N2-1の値をとる。

def print_nstar(n1):
  retstr=''
  if n1<= 0:
    return retstr
  for i in range(n1):
      retstr=retstr+'*'
  return retstr

for i in range (-1,5):
  print("Loto6:"+print_nstar(i))  
出力結果
Loto6:
Loto6:
Loto6:*
Loto6:**
Loto6:***
Loto6:****

パターン3)for 繰り返し変数 in range(N1,N2,Nst)

N1:開始値,N2:終了値,Nst:増減間隔
繰り返し変数の増減間隔を1以外にする場合、
このパターンを使う。
繰り返し変数はN1~N2-Nstをとる。

(1)増減値が正の時

#増減値が2
for i in range (-1,5,2):
  print("Loto6:"+str(i)+':'+print_nstar(i))
出力結果
Loto6:-1:
Loto6:1:*
Loto6:3:***

(2)増減値が負の時

#増減値が負
for i in range (5,1,-1):
  print("Loto6:"+str(i)+':'+print_nstar(i))
出力結果
Loto6:5:*****
Loto6:4:****
Loto6:3:***
Loto6:2:**

4.PHPでのfor

パターン)for(繰り返し変数=N1;繰り返し変数 演算子 N2;繰り返し変数 演算子 Nst)

N1:開始値,N2:終了値,Nst:増減間隔
PHPのforは上記で指定できる。
どんな場合も1本で済む。
終了値での〇〇以上、〇〇以下の指定ができるのが大きい
指定するものが多くて面倒くさい分、自由度が高い

<?php
// Your code here!
function getstar($n){
  $str0="";
  for($i=0;$i<$n;$i++){
    $str0=$str0."*";
  }
  $str0=$str0."\n";
  return $str0;
}
for($i=5;$i>=1;$i+=-1){
  print($i);
  print(getstar($i));
}
?>

終了値の1*がポイント

出力結果
5*****
4****
3***
2**
1*

5.さいごに

同じ繰り返し処理でも、単純にある回数だけ実行したいとか、
細かい条件を決めて実行したいとかあるだろう。
pythonのfor rangeには最小限のコードでやりたいことを実現できるようにしたい
との意図が見えるような気がした。
ただし、終了値の指定には気を付ける必要がある

0
0
0

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
0
0