Python While ループ ユーザー入力
このチュートリアルでは、Python で特定の条件が true になるまで複数のユーザーから入力を取得する方法について説明します。
Python3 の while ループ内のユーザー入力
ユーザーが必要な値を入力するまで入力を求め続けたい場合は、while ループ内で input() 関数を使用できます。
プログラミングでは、カウンター制御とセンチネル制御の 2 種類のループがあります。 カウンター制御ループでは、ループを実行する回数を指定しますが、センチネル制御ループでは、ループを実行するために "true" を保持する必要がある条件を指定します。
for ループはカウンター制御のループです。つまり、実行前にループを何回実行するかを指定する必要があります。
while ループはセンチネル制御のループです。つまり、特定の条件が満たされるまで実行し続けます。
これを行うには、ループの外で変数を初期化する必要があります。 次のコード スニペットは、input() 関数を while ループ内で使用する方法を示しています。
コード例:
name = "not maisam"
while name != "maisam":
name = input("please enter your name: ")
print("you guessed it right")
出力:
please enter your name: 123
please enter your name: abc
please enter your name: maisam
you guessed it right
上記のセクションのコードは、ユーザーが maisam を入力するまで、ユーザーにデータの入力を求め続けます。
Python2 の while ループ内のユーザー入力
残念ながら、上記の解決策は python2 では失敗します。
このために、input() 関数を raw_input() 関数に置き換える必要があります。 ユーザー入力を受け取り、入力から最後の \n を削除して結果を返します。
この [raw_input() 関数](raw_input — Python Reference (The Right Way) 0.1 documentation) は、python2 の input() 関数と同等です。 次のコード例は、while ループ内で raw_input() 関数を使用する方法を示しています。
コード例:
name = "not maisam"
while name != "maisam":
name = raw_input("please enter your name: ")
print "you guessed it right"
出力:
please enter your name: 123
please enter your name: abc
please enter your name: maisam
you guessed it right
上記のセクションのコードは、前の例と同じように機能し、ユーザーが maisam を入力するまで、ユーザーにデータの入力を求め続けます。
Maisam is a highly skilled and motivated Data Scientist. He has over 4 years of experience with Python programming language. He loves solving complex problems and sharing his results on the internet.
LinkedIn