LoginSignup
1
3

More than 3 years have passed since last update.

【Python】演算子(算術、比較、文字列)

Last updated at Posted at 2020-01-07

算術演算子( + , - , * , / , % , // , ** )

数値型の変数や数値に対して次の演算子で算術演算を行うことが出来る。

演算子 意味
+ 足し算
- 引き算
* 掛け算
/ 割り算
% 剰余
// 切り捨て除算
** べき乗
sample.py
a=5
b=2
print(a+b) #output=7
print(a-b) #output=3
print(a*b) #output=10
print(a/b) #output=2.5
print(a%b) #output=1
print(a//b) #output=2
print(a**b) #output=25

他にも、pandasなどのライブラリを使うことで行列の内積、外積、行列式の演算といったことも可能になる。

比較演算子( ==, > , < , >= , <= , is , in , is not , not in)

比較演算子はTrueまたはFalseを結果として返す。
(if文などの条件分岐では、このTrue/Falseによりif文内の処理が実行されるかどうかが決定される。)
このようなTrue/Falseを値として持つ変数をブール型変数と呼ぶ。

演算子 意味
a == b a,bが同じ値をもつときTrue
a>b a>bのときTrue
a<b a<bのときTrue
a>=b a>=bのときTrue
a<=b a<=bのときTrue
a is b aとbが同じidを持つときTrue(同一オブジェクトを指すかどうか)
a in b aがbの要素であるときTrue(同一の値を持つかどうか)
a is not b aとbが同じidを持たないときTrue(同一のオブジェクトをささないか)
a not in b aがbの要素でないTrue(同一の値を持つかどうか)
comp.py
a=1
b=1.0
print(id(a)) #output=140722308489616
print(id(b)) #output=1234075931664
print(a==b) #output=True
print(a is b) #output=False

ブール型変数同士の演算として以下のものがある。

演算子 意味
A and B A,BがともにTrueならばTrue
A or B AまたはBがTrueであればTrue
not A Aの真偽を逆にする
boolean.py
a=True
b=False
print(a and b) #output=False
print(a or b) #output=True
print(a and not b) #output=True

文字列演算( + , * , [ start : end ] )

str1、str2を文字型変数、numを整数とする。

演算子 意味
str1 + str2 str1とstr2が合体した文字列が生成される
str1*num str1がnum個生成される
str1[ start : end : step] str1のstart文字目からend文字目までをstep-1個飛ばしで取得
sample.py
a="abc"
b="def"
print(a+b) #output=abcdef
print(a*2) #output=abcabc
print(a[1:]) #output=bc
print(a[:1]) #output=a
print(a[::2]) #output=ac
1
3
3

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
1
3