情報の取得と処理の方法は、どのプログラミング言語においても、ユーザーから供給され取得される情報についてはより重要な倫理的側面の1つです。
Pythonは、CやJavaなどの他のプログラミング言語と比較すると、この点では比較的遅いですが、エンドユーザーから直接取得したデータを取得、分析、処理するための堅牢なツールを含んでいます。
この記事では、Pythonの input()
関数を通じてユーザーから情報を取得する方法を、例としていくつかのコードスニペットを用いて簡単に見ていきます。
Pythonでの入力
キーボードから情報を受け取るために、Python は input()
関数を使用します。
この関数にはオプションのパラメータがあり、一般にプロンプトと呼ばれる、関数が呼ばれるたびに画面に表示される文字列が指定されます。
Note: Python 3 が input()
関数を導入する以前は、ユーザー入力を読み取る際には raw_input()
関数を使用するのがよい方法でした。
Python 3では、raw_input()
関数は非推奨となり、input()
関数に置き換えられ、キーボードからユーザーの文字列を取得するために使われるようになりました。
そして、Python 2 の input()
関数はバージョン 3 で廃止されました。
Python 2の input()
関数が提供していたのと同じ機能を得るためには、Python 3では eval(input())
というステートメントを使用する必要があります。
input()関数が呼ばれると、ユーザがコマンドラインから入力を行うまでプログラムの流れは停止します。
実際にデータを入力するには、ユーザは文字列を入力した後に ENTER キーを押す必要があります。
通常、ENTER キーを押すと改行文字 (“n”`) が挿入されますが、この場合は改行されません。
入力された文字列は、単にアプリケーションに送信されます。
さて、input()
関数の基本的な理論を理解したところで、実際にPythonでどのように動作するのか見てみましょう。
# Python 3
txt = input("Type something to test this out: ")
print(f"Is this what you just said? {txt}")
先ほどのコードを実行すると、”Type something to test this out: “というメッセージが表示されます。
何かを入力すると、今入力したものが出力されます。
Type something to test this out: Let the Code be with you!
Is this what you just said? Let the Code be with you!
文字列と数値の入力
関数 input()
は、デフォルトでは、受け取った情報をすべて文字列に変換します。
前に示した例は、この動作を示しています。
一方、数値は元々文字列として入力されるため、明示的にそのように処理する必要があります。
次の例は、数値型の情報をどのように受け取るかを示している。
# An input is requested and stored in a variable
test_text = input ("Enter a number: ")
# Converts the string into an integer. If you need
# to convert the user input into the decimal format,
# the float() function is used instead of int()
test_number = int(test_text)
# Prints in the console the variable as requested
print ("The number you entered is: ", test_number)
先ほどのコードを実行すると、次のようになる。
Enter a number: 13
The number you entered is: 13
より一般的な方法は、入力の読み込みと整数への変換の両方を1行で行うことである。
test_number = int(input("Enter a number: "))
ユーザーが実際に整数を入力しなかった場合、入力された文字列が浮動小数点数であっても、このコードは例外を投げることを覚えておいてください。
入力読み込み時の例外処理について
ユーザーが有効な情報を入力できるようにするには、いくつかの方法があります。
そのうちの1つは、ユーザーがデータを入力する際に発生する可能性のあるすべてのエラーを処理する方法です。
このセクションでは、入力を読み取る際に発生する可能性のあるエラーに対して、いくつかの良いエラー処理方法を示します。
しかし、その前に(潜在的に)安全でないコードの例を見てみましょう。
test2word = input("Tell me your age: ")
test2num = int(test2word)
print("Wow! Your age is ", test2num)
このコードを実行した後、数字の3の代わりに “Three “という文字列を入力したとする。
Tell me your age: Three
ここで、文字列 “Three” を入力して int()
関数を呼び出すと、ValueError
例外が発生し、プログラムは停止するかクラッシュします。
では、このコードをどのようにすれば、ユーザーの入力をより安全に扱えるようになるか見てみましょう。
test3word = input("Tell me your lucky number: ")
try:
test3num = int(test3word)
print("This is a valid number! Your lucky number is: ", test3num)
except ValueError:
print("This is not a valid number. It isn't a number at all! This is a string, go and try again. Better luck next time!")
このコードブロックは新しい入力を評価します。
もし入力が文字列で表現された整数であれば、 int()
関数がそれを適切な整数に変換します。
そうでない場合は例外が発生しますが、アプリケーションをクラッシュさせるのではなく、例外をキャッチして2つ目の print
ステートメントを実行します。
以下は、例外が発生したときにこのコードが実行される例です。
Tell me your lucky number: Seven
This is not a valid number. It isn't a number at all! This is a string, go and try again. Better luck next time!
そして、これはPythonで入力関連のエラーがどのように処理されるかを示しています。
注意:このコードをwhileループのような他の構成要素と組み合わせることで、プログラムが要求する有効な整数入力を受け取るまで繰り返しコードを実行することができます。
完全な例
# Make a function that will contain the
# desired program.
def example():
# Call for an infinite loop that keeps executing
# until an exception occurs
while True:
test4word = input("What's your name? ")
try:
test4num = int(input("From 1 to 7, how many hours do you use your smartphone?" ))
# If something else that is not the string
# version of a number is introduced, the
# ValueError exception will be called.
except ValueError:
# The cycle will go on until validation
print("Error! This is not a number. Try again.")
# When successfully converted to an integer,
# the loop will end.
else:
print("Impressive, ", test4word, "! You spent", test4num*60, "minutes or", test4num*60*60, "seconds using your smartphone!")
break
# The function is called
example()
と出力されます。
What's your name? Francis
From 1 to 7, how many hours do you use your smartphone?
Impressive, Francis! You spent 180 minutes or 10800 seconds using your smartphone!
結論
この記事では、組み込みの Python input()
関数を使用して、さまざまな形式のユーザー入力を取得する方法について見ました。
また、ユーザー入力を取得する際に発生しうる例外やエラーをどのように処理するかも見てきました。