Python の変数とデータ型

PythonPythonBeginner
今すぐ練習

💡 このチュートリアルは英語版からAIによって翻訳されています。原文を確認するには、 ここをクリックしてください

はじめに

この実験では、Python の変数とデータ型の基本概念を学びます。変数は、コード内でデータを保存、アクセス、操作するためのプログラミングの基本的な構成要素です。さまざまなデータ型を理解することは、効果的な Python プログラムを作成するために不可欠です。

さまざまな変数を作成し、Python で利用可能なさまざまなデータ型を探索し、型変換を行い、式で変数を使用する方法を学びます。これらのスキルは Python プログラミングの基礎を形成し、より複雑なアプリケーションを開発するために必要です。

この実験の終わりまでに、Python でさまざまなデータ型の変数を作成して使用することに慣れるでしょう。


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL python(("Python")) -.-> python/BasicConceptsGroup(["Basic Concepts"]) python(("Python")) -.-> python/ControlFlowGroup(["Control Flow"]) python/BasicConceptsGroup -.-> python/variables_data_types("Variables and Data Types") python/BasicConceptsGroup -.-> python/numeric_types("Numeric Types") python/BasicConceptsGroup -.-> python/strings("Strings") python/BasicConceptsGroup -.-> python/booleans("Booleans") python/BasicConceptsGroup -.-> python/type_conversion("Type Conversion") python/ControlFlowGroup -.-> python/conditional_statements("Conditional Statements") subgraph Lab Skills python/variables_data_types -.-> lab-271605{{"Python の変数とデータ型"}} python/numeric_types -.-> lab-271605{{"Python の変数とデータ型"}} python/strings -.-> lab-271605{{"Python の変数とデータ型"}} python/booleans -.-> lab-271605{{"Python の変数とデータ型"}} python/type_conversion -.-> lab-271605{{"Python の変数とデータ型"}} python/conditional_statements -.-> lab-271605{{"Python の変数とデータ型"}} end

最初の Python 変数を作成する

このステップでは、Python で変数を作成して使用する方法を学びます。変数は、データ値を格納するコンテナであり、コード内で参照しやすいように意味のある名前を付けます。

まず、新しい Python ファイルを作成し、いくつかの基本的な変数を定義しましょう。

  1. WebIDE で /home/labex/project/variables.py ファイルを開きます。

  2. 以下のコードを追加して、3 つの変数を定義します。

## Creating basic variables
water_supply = 100    ## Amount of water in gallons
food_supply = 50      ## Amount of food in pounds
ammunition = 40       ## Number of ammunition rounds

Python では、名前を指定し、その後に等号 (=) を付け、その後に割り当てたい値を指定することで変数を作成します。

  1. これらの変数の値を表示するコードを追加しましょう。
## Displaying variable values
print("Water supply:", water_supply)
print("Food supply:", food_supply)
print("Ammunition:", ammunition)
  1. WebIDE でターミナルを開き、以下のコマンドを実行してスクリプトを実行します。
python3 /home/labex/project/variables.py

以下の出力が表示されるはずです。

Water supply: 100
Food supply: 50
Ammunition: 40

おめでとうございます。最初の Python 変数を作成し、その値を表示しました。これらの変数は、プログラムがアクセスして操作できる情報を格納しています。

数値データ型の理解

Python には、さまざまな種類のデータを分類するために使用されるいくつかのデータ型があります。このステップでは、整数 (integer) と浮動小数点数 (float) という 2 つの数値データ型について学びます。

  1. WebIDE で /home/labex/project/variables.py ファイルを開きます。

  2. 以下のコードをファイルに追加して、異なる数値データ型の変数を定義します。

## Numeric data types
integer_value = 42        ## Integer (whole number)
float_value = 3.14159     ## Float (decimal number)
  1. type() 関数を使用して、これらの変数の型を調べましょう。
## Check the data types
print("\nUnderstanding data types:")
print("integer_value:", integer_value, "- Type:", type(integer_value))
print("float_value:", float_value, "- Type:", type(float_value))
  1. これらの数値型を使っていくつかの基本的な演算を行いましょう。
## Basic operations with numbers
sum_result = integer_value + float_value
product_result = integer_value * float_value

print("\nBasic operations:")
print(f"{integer_value} + {float_value} = {sum_result}")
print(f"{integer_value} * {float_value} = {product_result}")
  1. スクリプトを実行します。
python3 /home/labex/project/variables.py

以下のような出力が表示されるはずです。

Water supply: 100
Food supply: 50
Ammunition: 40

Understanding data types:
integer_value: 42 - Type: <class 'int'>
float_value: 3.14159 - Type: <class 'float'>

Basic operations:
42 + 3.14159 = 45.14159
42 * 3.14159 = 131.94678

整数と浮動小数点数を使って演算を行うと、必要に応じて Python が結果を自動的に浮動小数点数に変換することに注意してください。

文字列とブール値の操作

数値データ型に加えて、Python はテキストデータ用の文字列 (string) と真偽値用のブール値 (boolean) を提供しています。これらの型について調べてみましょう。

  1. WebIDE で /home/labex/project/variables.py ファイルを開きます。

  2. 以下のコードを追加して、文字列とブール値の変数を定義します。

## String data type - for text
camp_name = "Python Base Camp"
location = 'Programming Valley'  ## Strings can use single or double quotes

## Boolean data type - for true/false values
is_safe = True
has_water = True
enemy_nearby = False
  1. これらの変数をチェックして表示するコードを追加します。
## Displaying string and boolean variables
print("\nString variables:")
print("Camp name:", camp_name, "- Type:", type(camp_name))
print("Location:", location, "- Type:", type(location))

print("\nBoolean variables:")
print("Is the camp safe?", is_safe, "- Type:", type(is_safe))
print("Is water available?", has_water, "- Type:", type(has_water))
print("Is enemy nearby?", enemy_nearby, "- Type:", type(enemy_nearby))
  1. いくつかの文字列操作も実演しましょう。
## String operations
full_location = camp_name + " in " + location
print("\nFull location:", full_location)

## String repetition
border = "-" * 20
print(border)
print("Camp Information")
print(border)
  1. スクリプトを実行します。
python3 /home/labex/project/variables.py

以下のような出力が表示されるはずです。

Water supply: 100
Food supply: 50
Ammunition: 40

Understanding data types:
integer_value: 42 - Type: <class 'int'>
float_value: 3.14159 - Type: <class 'float'>

Basic operations:
42 + 3.14159 = 45.14159
42 * 3.14159 = 131.94678

String variables:
Camp name: Python Base Camp - Type: <class 'str'>
Location: Programming Valley - Type: <class 'str'>

Boolean variables:
Is the camp safe? True - Type: <class 'bool'>
Is water available? True - Type: <class 'bool'>
Is enemy nearby? False - Type: <class 'bool'>

Full location: Python Base Camp in Programming Valley
--------------------
Camp Information
--------------------

文字列は + 演算子で連結でき、* 演算子で繰り返すことができることに注意してください。ブール値は条件を表現し、プログラムの流れを制御するのに便利です。

型変換と型チェック

時には、値をあるデータ型から別のデータ型に変換したり、変数のデータ型をチェックする必要があります。これを型変換 (type conversion または type casting) と呼びます。この概念について調べてみましょう。

  1. WebIDE で /home/labex/project/variables.py ファイルを開きます。

  2. 型変換を実演するコードを追加します。

## Type conversion examples
print("\nType Conversion Examples:")

## Converting string to integer
supplies_str = "75"
supplies_int = int(supplies_str)
print(f"String '{supplies_str}' converted to integer: {supplies_int} - Type: {type(supplies_int)}")

## Converting integer to string
days_int = 30
days_str = str(days_int)
print(f"Integer {days_int} converted to string: '{days_str}' - Type: {type(days_str)}")

## Converting integer to float
distance_int = 100
distance_float = float(distance_int)
print(f"Integer {distance_int} converted to float: {distance_float} - Type: {type(distance_float)}")

## Converting float to integer (note: this truncates the decimal part)
temperature_float = 32.7
temperature_int = int(temperature_float)
print(f"Float {temperature_float} converted to integer: {temperature_int} - Type: {type(temperature_int)}")
  1. データ型をチェックするコードを追加します。
## Type checking
print("\nType Checking Examples:")
value1 = 42
value2 = "42"
value3 = 42.0

print(f"Is {value1} an integer? {isinstance(value1, int)}")
print(f"Is {value2} an integer? {isinstance(value2, int)}")
print(f"Is {value3} a float? {isinstance(value3, float)}")
print(f"Is {value2} a string? {isinstance(value2, str)}")
  1. スクリプトを実行します。
python3 /home/labex/project/variables.py

以下のような出力が表示されるはずです。

...previous output...

Type Conversion Examples:
String '75' converted to integer: 75 - Type: <class 'int'>
Integer 30 converted to string: '30' - Type: <class 'str'>
Integer 100 converted to float: 100.0 - Type: <class 'float'>
Float 32.7 converted to integer: 32 - Type: <class 'int'>

Type Checking Examples:
Is 42 an integer? True
Is 42 an integer? False
Is 42.0 a float? True
Is 42 a string? True

以下の点に注意してください。

  • int() は値を整数に変換します。
  • float() は値を浮動小数点数に変換します。
  • str() は値を文字列に変換します。
  • 浮動小数点数を整数に変換するとき、小数部分は切り捨てられます (四捨五入されません)。
  • isinstance() 関数は、変数が特定の型であるかどうかをチェックします。

これらの変換関数は、ユーザーからの入力を処理するときや、異なるソースからのデータを扱うときに便利です。

式と判断処理における変数の使用

変数は、式や判断構造の中で使用されるときに本当の力を発揮します。計算や条件文の中で変数をどのように使うかを見ていきましょう。

  1. WebIDE で /home/labex/project/variables.py ファイルを開きます。

  2. 計算で変数を使用する例を示すコードを追加します。

## Variables in expressions
print("\nVariables in Expressions:")

water_per_day = 4  ## gallons
food_per_day = 2.5  ## pounds

## Calculate how long supplies will last
water_days = water_supply / water_per_day
food_days = food_supply / food_per_day

print(f"With {water_supply} gallons of water, consuming {water_per_day} gallons per day, water will last {water_days} days")
print(f"With {food_supply} pounds of food, consuming {food_per_day} pounds per day, food will last {food_days} days")
  1. 条件文で変数を使用する例を示すコードを追加します。
## Using variables for decision making
print("\nDecision Making with Variables:")

## Check which supply will run out first
if water_days < food_days:
    limiting_factor = "Water"
    limiting_days = water_days
else:
    limiting_factor = "Food"
    limiting_days = food_days

print(f"{limiting_factor} will run out first, after {limiting_days} days")

## Check if supplies are sufficient for a 10-day journey
journey_days = 10
sufficient_supplies = water_days >= journey_days and food_days >= journey_days and ammunition >= 20

print(f"Planning a {journey_days}-day journey.")
print(f"Do we have sufficient supplies? {sufficient_supplies}")

## Provide specific supply status
if water_days < journey_days:
    print(f"Warning: Water will only last {water_days:.1f} days.")
if food_days < journey_days:
    print(f"Warning: Food will only last {food_days:.1f} days.")
if ammunition < 20:
    print(f"Warning: Only {ammunition} rounds of ammunition available.")
  1. スクリプトを実行します。
python3 /home/labex/project/variables.py

以下のような出力が表示されるはずです。

...previous output...

Variables in Expressions:
With 100 gallons of water, consuming 4 gallons per day, water will last 25.0 days
With 50 pounds of food, consuming 2.5 pounds per day, food will last 20.0 days

Decision Making with Variables:
Food will run out first, after 20.0 days
Planning a 10-day journey.
Do we have sufficient supplies? True

これは、数学的な計算で変数をどのように使うことができるか、そして変数の値に基づいてどのように判断を下すかを示しています。比較演算子 (<, >=) と論理演算子 (and) を使って条件を作成する方法に注目してください。

書式指定構文 {water_days:.1f} は、浮動小数点数を小数点以下 1 桁で表示することを指定しています。

まとめ

この実験では、Python の変数とデータ型の基本概念を学びました。以下を含むさまざまな型の変数を作成し、使用しました。

  • 整数 (整数値用)
  • 浮動小数点数 (小数値用)
  • 文字列 (テキストデータ用)
  • ブール値 (真偽値用)

また、以下のことも学びました。

  • type() 関数を使用して変数の型をチェックする方法
  • int()float()str() などの関数を使用して異なるデータ型間で変換する方法
  • 式や計算で変数を使用する方法
  • 条件文を使用して変数の値に基づいて判断を下す方法

これらの概念は Python プログラミングの基礎を形成しています。変数を使うことでデータを保存し、操作することができます。また、異なるデータ型を理解することで、それぞれの状況に適した型を使うことができます。Python の学習を続けるにつれて、これらの基礎を元により複雑で強力なプログラムを作成するようになります。