0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

変数と基本的なデータ型について、より詳しく説明いたします。

1. 変数

Pythonでは、変数は値を格納するためのコンテナのようなものです。変数名は文字またはアンダースコア(_)で始まり、文字、数字、アンダースコアを含むことができます。

x = 5
name = "John"
_private = True

Pythonは動的型付け言語なので、変数の型を明示的に宣言する必要はありません。変数の型は、それに割り当てられた値によって自動的に決定されます。

2. 基本的なデータ型

Pythonには以下の基本的なデータ型があります:

a. 数値型

  • 整数 (int):全ての整数
  • 浮動小数点数 (float):小数点を含む数
  • 複素数 (complex):虚数を含む数
integer = 42
float_number = 3.14
complex_number = 1 + 2j

print(type(integer))       # <class 'int'>
print(type(float_number))  # <class 'float'>
print(type(complex_number))# <class 'complex'>

b. 文字列 (str):

文字列は、シングルクォート(' ')またはダブルクォート(" ")で囲まれたテキストです。

single_quoted = 'Hello'
double_quoted = "World"
multi_line = '''This is a
multi-line string'''

print(single_quoted + " " + double_quoted)  # Hello World
print(len(multi_line))  # 文字列の長さを表示

c. ブール型 (bool):

True または False の2つの値のみを持ちます。

is_python_fun = True
is_coding_hard = False

print(is_python_fun and is_coding_hard)  # False
print(is_python_fun or is_coding_hard)   # True
print(not is_python_fun)                 # False

d. None型:

Noneは特殊な値で、「値がない」ことを表します。

result = None
print(result is None)  # True

3. 型変換

Pythonでは、異なる型の間で変換を行うことができます。

# 文字列から整数へ
age_str = "25"
age_int = int(age_str)
print(age_int + 5)  # 30

# 整数から浮動小数点数へ
x = 10
y = float(x)
print(y)  # 10.0

# 数値から文字列へ
num = 42
num_str = str(num)
print("The answer is " + num_str)  # The answer is 42

4. 型の確認

type() 関数を使用して、変数の型を確認できます。

x = 5
y = "Hello"
z = 3.14

print(type(x))  # <class 'int'>
print(type(y))  # <class 'str'>
print(type(z))  # <class 'float'>

5. 変数の命名規則

  • 変数名は文字またはアンダースコアで始める必要があります。
  • 大文字と小文字は区別されます(age と Age は異なる変数です)。
  • 予約語(if, for, whileなど)は変数名として使用できません。
# 良い例
user_name = "Alice"
age_of_user = 30
_private_variable = "Secret"

# 悪い例
# 2user = "Bob"  # 数字で始まっているためエラー
# if = 10        # 予約語を使用しているためエラー

これらの基本的なデータ型と変数の概念を理解することは、Pythonプログラミングの基礎となります。これらを適切に使用することで、様々な種類のデータを効果的に扱い、複雑なプログラムを構築することができます。

0
0
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?