1. ホーム
  2. スクリプト・コラム
  3. パイソン

Python 入出力と高次代入の基礎知識

2022-01-08 10:44:14

1. 入力、出力、およびコメント

1.1 ユーザーからの入力の取得

プログラムはしばしば、ユーザーから送信されたデータを取得するためにユーザーと対話する必要があります。Pythonは、ユーザーの入力を受け取り、文字列への参照を返すinput関数を提供します。
input関数は、ユーザーに入力を促すためのテキストとして使用される文字列を引数として受け取るため、プロンプト文字列とも呼ばれる。

>>> number = input('Enter the number of students: ')
Enter the number of students: 52
>>> number
'52'


対話型インタプリタ number = input('Enter the number of students: ') で1行目を実行すると、 "Enter the number of students: " という文字列が出力され、ユーザに適切な情報を求めるプロンプトが表示されます。ここでは、52 と入力して Enter キーを押すと、プロンプト文字列の後にユーザーの入力が得られ、number 変数に格納されます。input関数が返す値は文字列型であることに注意してください。この文字列を別の型に変換する必要がある場合は、目的の操作を実行するために適切な型変換を用意する必要があります。

>>> score = input('Enter the total score: ')
Enter the total score: 4396
>>> number = input('Enter the number of students: ')
Enter the number of students: 52
>>> average_score = int(score) / int(number)
>>> average_score
84.53846153846153


1.2 出力の書式設定

1.2.1 基本的なメソッド

上記の例でprint関数を何度も見てきましたが、これはPythonの出力を印刷する非常に簡単な方法を提供します。これは0個以上の引数を取り、デフォルトでは結果を表示するセパレータとして1つのスペースを使いますが、オプションのsep引数で変更することができます。さらに、デフォルトでは、すべてのプリントは改行で終わりますが、これは end パラメータを

>>> print('Data', 'Structure', 'and', 'Algorithms')
Data Structure and Algorithms
>>> print('Data', 'Structure', 'and', 'Algorithms', sep='-')
Data-Structure-and-Algorithms
>>> print('Data', 'Structure', 'and', 'Algorithms', sep='-', end='!!!')
Data-Structure-and-Algorithms!!! >>>


フォーマットされた文字列は、変更されない単語またはスペースと、後で挿入される変数のプレースホルダーを含むテンプレートです。フォーマットされた文字列では、実行時変数の値によって変更が発生することがあります。

print("The price of %s is %d yuan." % (fruit, price)) 


は文字列演算子で、書式演算子として知られています。式の左側はテンプレート(フォーマット文字列とも呼ばれる)、右側は文字列をフォーマットするための一連の値で、右側の値の数はフォーマット文字列の % の数と一致します。これらの値は、左から右へとフォーマット文字列に入れ替わります。

フォーマット文字列は、1つ以上の変換文を含むことができます。変換文は、どのようなタイプの値が適切な位置で文字列に挿入されるかをフォーマット演算子に伝えます。上記の例では、%sは文字列を、%dは整数を宣言しています。

より複雑な出力書式を設定するために,% と書式設定文字の間に書式設定修飾子を追加することができます。

>>> print("The price of %s is %d yuan." % ('apple', fruits['apple']))
The price of apple is 5 yuan.
>>> print("The price of %s is %10d yuan." % ('apple', fruits['apple']))
The price of apple is 5 yuan.
>>> print("The price of %s is %+10d yuan." % ('apple', fruits['apple']))
The price of apple is +5 yuan.
>>> print("The price of %s is %-10d yuan." % ('apple', fruits['apple']))
The price of apple is 5 yuan.
>>> print("The price of %s is %10.3f yuan." % ('apple', fruits['apple']))
The price of apple is 5.000 yuan.
>>> print("The price of apple is %(apple)f yuan." % fruits)
The price of apple is 5.000000 yuan.


1.2.2 書式設定機能

上記のアプローチもまだ有効ですが、推奨される代替案はテンプレート文字列フォーマットです。これは、以前のアプローチの利点を取り入れ、強化することによって、基本的なフォーマットのメカニズムを簡素化するように設計されています。フォーマット関数を使用する場合,各置換フィールドは括弧で囲まれ,変数名を含むことができ,置換フィールドは名前を持たないか,名前としてインデックスを使用することができます:。

>>> "The price of {} is {} yuan.".format('apple', 5.0)
'The price of apple is 5.0 yuan.'
>>> "The price of {fruit} is {price} yuan.".format(fruit='apple', price=price)
'The price of apple is 5.0 yuan.'
>>> "The price of {1} is {0} yuan.".format(5.0, 'apple')
'The price of apple is 5.0 yuan.'


上の例からわかるように、インデックスと変数名の順番は関係ない。これに加えて、コロン : を組み合わせることで書式指定子(%演算子に似ている)を利用している。

>>> value = 2.718281828459045
>>> '{} is approximately {:.2f}'.format('e', value)
'e is approximately 2.72'
>>> '{} is approximately {:+.2f}'.format('e', value)
'e is approximately +2.72'
>>> '{} is approximately {:0>10.2f}'.format('e', value)
'e is approximately 0000002.72'
>>> '{} is approximately {:0<10.2f}'.format('e', value)
'e is approximately 2.72000000'
>>> '{} is approximately {:^10.2f}'.format('e', value)
'e is approximately 2.72 '
>>> '{:,}'.format(100000)
'100,000'
>>> '{} is approximately {:.2%}'.format('e', value)
'e is approximately 271.83%'
>>> '{} is approximately {:.4e}'.format('e', value)
'e is approximately 2.7183e+00'
>>> '{} is approximately {:0=+10.2f}'.format('e', value)
'e is approximately +000002.72'


以上の例から、: 記号は、幅、精度、千区切り、 ^, <, > をそれぞれ中央揃え、左揃え、右揃えに指定でき、その後に width を指定でき、パディングに一文字、デフォルトではスペース、指定子=で記号と数字の間にパディング文字が入ることを指定できることが簡単にまとめられます。
同様に、データ型の変換にはb、d、o、x、2進数、10進数、8進数、16進数、データをUnicodeコードに変換するにはcを使用します。

>>> "The number is {num:b}".format(num=1024)
'The number is 10000000000'
>>> "The number is {num:d}".format(num=1024)
'The number is 1024'
>>> "The number is {num:o}".format(num=1024)
'The number is 2000'
>>> "The number is {num:x}".format(num=1024)
'The number is 400'
>>> "The number is {num:c}".format(num=1024)
'The number is Ѐ'


1.3 アノテーション

プログラムの読みやすさを向上させる優れた方法であり、見落としがちなポイントでもあるコメントを紹介しましょう。Pythonは#シンボルの直後のテキストを解釈しません。

radius = 5.0 # radius of the circle
side = 2.0 # length of the side of the square
# The difference between the area of the square and the area of the circle
area_c = 3.14 * radius ** 2
area_s = side ** 2
diff = area_s - area_c


複数行のコメントを使用する場合は、3つのダブルクォート(""")または3つのシングルクォート('')のペアの間にコメント文を配置することができます。

radius = 5.0
side = 2.0
area_c = 3.14 * radius ** 2
area_s = side ** 2
diff = area_s - area_c


2. 高次の代入文

変数やデータ構造のデータ要素に値を代入する方法を学びましたが、他にもコードを簡略化して読みやすくするために使えるタイプの代入文があります。

2.1 代入演算子

基本的な=の代入演算子に加えて、右辺の式の標準演算子を代入演算子=の前に移動して、+=、-=、*=、/=、%=などの新しい演算子を構成することができる。

>>> number = 1
>>> number += 4
>>> print(number)
5
>>> number //= 2
>>> print(number)
2
>>> number **= 2
>>> print(number)
4
>>> string_1 = 'Hello!
>>> string_1 *= 2
>>> print(string_1)
'Hello!


この代入は、数値データだけでなく、他のデータ型にも使用できます(データ型が使用する二項演算子をサポートしている限り)。

2.2 並列代入

1つずつ代入する以外に、複数の変数を同時に(並列に)代入することができます。

>>> a, b, c, d = 0, 1, 2, 3
>>> print(a, b, c, d)
0 1 2 3


このように、複数の変数の値を単純に入れ替えることができます。

>>> b, c = c, b
>>> print(a, b, c, d)
0 2 1 3


2.3 シーケンスアンパッキング

シーケンシャル・アンラップとは、反復可能なオブジェクトをアンラップして、その結果の値を一連の変数に格納する処理ですが、アンラップするシーケンスは、等号の左側にリストされた変数と同じ数の要素を含んでいなければならず、そうでない場合は例外がスローされます。

>>> fruit, price = ['apple', 5.0]
>>> print(fruit)
apple
>>> print(price)
5.0
>>> fruit, price, date = ('apple', 5.0)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: not enough values to unpack (expected 3, got 2)
>>> fruit, price = ('apple', 5.0, '2021-11-11')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: too many values to unpack (expected 2)


例外の発生を避けるために、アスタリスク演算子 * を使って余分な値を集めると、値と変数の数が同じであることを確認する必要がなくなり、代入文の右辺は任意の型のシーケンスにできますが、アスタリスクが付いた変数は常にリストで終わります。

>>> fruits = ['apple', 'orange', 'lemon']
>>> fruit_a, *rest = fruits
>>> print(rest)
['orange', 'lemon']
>>> fruits_a, *rest, fruits_b = fruits
>>> print(rest)
['orange']
>>> fruits_a, fruits_b, fruits_c, *rest = fruits
>>> print(rest)
[]


2.4 チェーンの割り当て

連鎖的な代入は、複数の変数を同じ値に関連付けることができます。

var_1 = var_2 = value


に相当する。

var_1 = value
var_2 = var_1


概要

この記事があなたのお役に立ち、Script Houseの他のコンテンツにもっと注目していただけることを願っています。