お勉強ダイアログ

プログラミングの勉強した内容を自分のために書き残してるだけです

ループに挑戦

今回は、Pythonのループを試していきたいと思います。

Pythonのループ

Pythonのループはwhileとforの2つ。
whileは

while 継続条件:
    処理

ifのときと同じように、インデントがwhile内の処理かの判定条件になるよう。

forは

for 変数1 in 変数2:
    処理

で変数2の要素を1つづつ変数1に格納して処理を回す。

while文を使ってみる

while文つかって1~10まで表示するプログラムを書いてみる。

count = 1
while count < 11:
    print(count)
    count += 1
print("End")

結果はこう

f:id:ku-k669500:20180121163807p:plain

うまくいった!

次は、1~100までで9の倍数だけ表示するプログラムをつくる。

count = 1
while count < 101:
    if count % 9 = 0:
        printf(count)
    count += 1
print("End")

だと!

f:id:ku-k669500:20180121164450p:plain

そうですね=が足りないですね。。。
そして、javaの癖でprint"f"にしていた。。。

count = 1
while count < 101:
    if count % 9 == 0:
        print(count)
    count += 1
print("End")

これでどうだ!!

f:id:ku-k669500:20180121164800p:plain

よかった。うまくいった。

for文を使ってみる

for文で「Hello World」をバラバラにして表示してみる。

helloworld = "Hello World"
for word in helloworld:
    print(word)
print("End")

すると

f:id:ku-k669500:20180121165446p:plain

OK!!!!

おわりに

Pythonも他の言語を同じようにwileもforもある。
けど、使い方を明確に分けているみたい。
わかりやすくていいかも。他の言語だと何が違うのかよくわからないし。