Python 繰り返し構文 while、for

Python

Pythonでの繰り返しの構文を記載します。

Pythonバージョン:3.8.8

while

ブロック内の式を、条件式が満たされる限り繰り返す

[st-mybox title=”” fontawesome=”” color=”#757575″ bordercolor=”#ccc” bgcolor=”#ffffff” borderwidth=”2″ borderradius=”2″ titleweight=”bold” fontsize=”” myclass=”st-mybox-class” margin=”25px 0 25px 0″]

構文
while 条件式
    ブロック(式)

[/st-mybox]

例)数字の1~5を出力する

whileは、条件式(i<6)がtrueであれば、式を実行するので、
iが6になった時点で、6<6となり、falseとなるので、繰り返しが終わる。

[st-mybox title=”” fontawesome=”” color=”#757575″ bordercolor=”#f3f3f3″ bgcolor=”#f3f3f3″ borderwidth=”0″ borderradius=”5″ titleweight=”bold” fontsize=”” myclass=”st-mybox-class” margin=”25px 0 25px 0″]

i=1
while i < 6:
print(i)
i+=1

[/st-mybox]

 

[st-mybox title=”” fontawesome=”” color=”#757575″ bordercolor=”#f3f3f3″ bgcolor=”#f3f3f3″ borderwidth=”0″ borderradius=”5″ titleweight=”bold” fontsize=”” myclass=”st-mybox-class” margin=”25px 0 25px 0″]

実行結果
1
2
3
4
5

[/st-mybox]

for

listの値を1つ目から順に変数に入れ、繰り返し実行していく。

構文
[st-mybox title=”” fontawesome=”” color=”#757575″ bordercolor=”#ccc” bgcolor=”#ffffff” borderwidth=”2″ borderradius=”2″ titleweight=”bold” fontsize=”” myclass=”st-mybox-class” margin=”25px 0 25px 0″]

for 変数 in リスト:
    式

[/st-mybox]

 

例)数字の1~5を出力する

listの値を1つ目から順にdataに入れ、繰り返し実行していく。

[st-mybox title=”” fontawesome=”” color=”#757575″ bordercolor=”#f3f3f3″ bgcolor=”#f3f3f3″ borderwidth=”0″ borderradius=”5″ titleweight=”bold” fontsize=”” myclass=”st-mybox-class” margin=”25px 0 25px 0″]

list=[1,2,3,4,5]
for data in list:
print(data)

[/st-mybox]

 

[st-mybox title=”” fontawesome=”” color=”#757575″ bordercolor=”#f3f3f3″ bgcolor=”#f3f3f3″ borderwidth=”0″ borderradius=”5″ titleweight=”bold” fontsize=”” myclass=”st-mybox-class” margin=”25px 0 25px 0″]

実行結果
1
2
3
4
5

[/st-mybox]

コメント

タイトルとURLをコピーしました