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 変数 チュートリアル

0
Posted at

はじめに

pythonの変数についてのチュートリアルです。

変数の宣言のやりかた

<変数名> = <値>で変数の宣言ができる。
他の言語と違い型の宣言が必要ない。

変数宣言
num = 1 #int
string = "word" #str
bol = True #boolean

pirnt(num) # 1
print(string) # word
print(bol) # True

関数も変数に格納できる

定義された関数を変数に格納でき、変数名で実行できる

関数の格納
def sample_func():
    print("functioin message")

func = sample_func
func() # function message

型の確認方法

print(type(<変数>))のようにtype()を使うと型を確認できる

型の確認
num = 123
bol = True

print(type(num)) # <class int>
print(type(bol)) # <class boolean>

型の変換

int(),str()などの組み込み関数で型変換をすることができる

型変換
string = "123" # strで宣言
    bol = True # booleanで宣言

int_for_str = int(string)
str_for_boolean = str(bol)
print(int_for_str, type(int_for_str)) # 123 int
print(str_for_boolean, type(str_for_boolean)) # True str

型変換の注意点
型の宣言をしないので思いがけない型変換でバグが生まれる可能性がある
型の変換を行う際は変数名を変えて格納するとバグの予防になる

一応型の宣言はできるが右辺の値で型を把握できるので必要ない
また、宣言によって型変換を防止することはできない

変数にできない値

変数の一文字目は数字にすることができない

禁止された変数
1word = "hello"
print(1word)

#! SyntaxError: invalid decimal literal

if,forなどすでに予約されている単語は使用できない

禁止された変数
if = 123
print(if)

#! SyntaxError: invalid syntax

おわりに

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?