Python での大文字と小文字の切り替え (置換)
この記事では、Python の Switch Case (置換) を理解しようとします。
Python での Switch Case の置き換えは何ですか?
これまでに使用してきた他のプログラミング言語とは異なり、Python には switch ステートメントや case ステートメントがありません。この事実を回避するために、辞書マッピングを使用します。
方法 1: ディクショナリ マッピングを使用して Python でスイッチケースを実装する
Python では、ディクショナリは、データ値を格納するために使用できる、順序付けされていないデータ値のコレクションです。要素ごとに 1 つの値しか含めることができない他のデータ型とは異なり、ディクショナリにはキーと値のペアを含めることもできます。
のキー値 辞書 ディクショナリを使用して Switch case ステートメントを置き換える場合、データ型は switch ステートメントの case として機能します。
Python3
# Function to convert number into string> # Switcher is dictionary data type here> def> numbers_to_strings(argument):> > switcher> => {> > 0> :> 'zero'> ,> > 1> :> 'one'> ,> > 2> :> 'two'> ,> > }> > # get() method of dictionary data type returns> > # value of passed argument if it is present> > # in dictionary otherwise second argument will> > # be assigned as default value of passed argument> > return> switcher.get(argument,> 'nothing'> )> # Driver program> if> __name__> => => '__main__'> :> > argument> => 0> > print> (numbers_to_strings(argument))> |
出力
zero
方法 2: if-else を使用して Python でスイッチケースを実装する
の if-else は、スイッチケースの交換を実装する別の方法です。これは、特定のステートメントまたはステートメントのブロックが実行されるかどうか、つまり、特定の条件が true である場合にステートメントのブロックが実行されるかどうかを決定するために使用されます。
Python3
bike> => 'Yamaha'> if> bike> => => 'Hero'> :> > print> (> 'bike is Hero'> )> elif> bike> => => 'Suzuki'> :> > print> (> 'bike is Suzuki'> )> elif> bike> => => 'Yamaha'> :> > print> (> 'bike is Yamaha'> )> else> :> > print> (> 'Please choose correct answer'> )> |
出力
bike is Yamaha
方法 3: クラスを使用して Python で Switch Case を実装する
このメソッドでは、クラスを使用して Python スイッチ内に switch メソッドを作成しています。 Pythonのクラス 。
Python3
class> Python_Switch:> > def> day(> self> , month):> > default> => 'Incorrect day'> > return> getattr> (> self> ,> 'case_'> +> str> (month),> lambda> : default)()> > def> case_1(> self> ):> > return> 'Jan'> > def> case_2(> self> ):> > return> 'Feb'> > def> case_3(> self> ):> > return> 'Mar'> my_switch> => Python_Switch()> print> (my_switch.day(> 1> ))> print> (my_switch.day(> 3> ))> |
出力
Jan Mar
Python で大文字と小文字を切り替える
Python 3.10 以降では、Python は次を使用してこれをサポートします。 マッチ スイッチの代わりに:
Python3
# This code runs only in python 3.10 or above versions> def> number_to_string(argument):> > match argument:> > case> 0> :> > return> 'zero'> > case> 1> :> > return> 'one'> > case> 2> :> > return> 'two'> > case default:> > return> 'something'> > head> => number_to_string(> 2> )> print> (head)> |
これは、 C++ 、 Java などの switch ケースに似ています。