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?

はじめに

こんにちは!
今回も、備忘録を兼ねて。

Pythonでプログラミングをする上で、変数やデータ型は、とても大事ですね。
変数はデータを入れる箱のようなもので、データ型はその箱に入るデータの種類を表します。

今回はPythonの変数とデータ型について、解説していきます。

変数とは?

変数とは、データを格納するための名前付きのメモリ領域です。
変数名 = 値」のように書くことで、値を変数に代入することができます。

# 変数の定義と代入
name = "やました" 
age = 20
height = 170.5

# 変数の値を表示
print(name)   # 出力結果: やました
print(age)    # 出力結果: 20
print(height) # 出力結果: 170.5 

データ型の種類

Pythonには、様々なデータ型が存在します。
代表的なデータ型は以下の通りです。

データ型 説明
整数(int) 整数を表す 10, -5, 0
浮動小数点数(float) 小数を表す 3.14, -2.7, 0.0
文字列(str) 文字列を表す "Hello", "Python"
ブール値(bool) 真理値を表す。 True (真) または False (偽) のいずれか。 True, False
リスト(list) 複数の値を順番に格納する。 [1, 2, 3], ["apple", "banana"]
タプル(tuple) 複数の値を順番に格納する。ただし、値の変更は不可。 (1, 2, 3), ("apple", "banana")
辞書(dict) キーと値のペアでデータを格納する。 {"name": "やました", "age": 20}
集合(set) 重複のない要素の集合を表す。 {1, 2, 3}, {"apple", "banana"}
NoneType 値が存在しないことを表す None という特別な値のみを持つ。 None

データ型の確認

type()関数を使うと、変数に格納されているデータの型を確認することができます。

name = "やました"
age = 20
height = 170.5
is_student = True

print(type(name))       # 出力結果: <class 'str'>
print(type(age))        # 出力結果: <class 'int'>
print(type(height))     # 出力結果: <class 'float'>
print(type(is_student)) # 出力結果: <class 'bool'> 

型変換

あるデータ型から別のデータ型に変換することを型変換と言います。

# 整数を文字列に変換
age = 20
age_str = str(age) 
print(age_str)   # 出力結果: "20"
print(type(age_str)) # 出力結果: <class 'str'>

# 文字列を整数に変換
age_str = "20"
age = int(age_str)
print(age)      # 出力結果: 20
print(type(age))  # 出力結果: <class 'int'>

変数の命名規則

変数名は自由に付けることができますが、以下のルールに従う必要があります。

  • 使用できる文字は、英数字とアンダースコア(_)のみ
  • 最初に数字を使うことはできない
  • Pythonの予約語(if, else, whileなど)は変数名として使えない
  • 大文字と小文字は区別される

まとめ

今回は、Pythonの変数とデータ型について解説しました。

変数とデータ型は、Pythonプログラミングの基礎であり、これらをしっかりと理解することで、より良いプログラムを作成することができます。

みなさんも一緒にがんばりましょう!

0
0
2

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?