Python3の基礎文法
(2020/10/13 12:35更新)
Pythonの基本的な文法について改めて再学習をしています。
今後再学習した項目を増やしていく予定です。
目次
演算子
算術演算子
演算子 | 演算内容 | 例 |
---|---|---|
+ | 加算 | 5 + 5 = 10 |
- | 減算 | 5 - 2 = 3 |
* | 乗算 | 2 * 3 = 6 |
/ | 除算 | 3 / 2 = 1.5 |
% | 剰余 | 5 % 2 = 1 |
** | 累乗 | 2 ** 4 = 16 |
// | 切り捨て除算 | 3 // 2 = 1 |
比較演算子
演算子 | 意味 |
---|---|
> | 大なり |
>= | 以上 |
< | 小なり |
<= | 以下 |
== | 等しい(同値性) |
!= | 等しくない(同値性) |
is | 等しい(オブジェクトの同一性) |
is not | 等しくない(オブジェクトの同一性) |
論理演算子
演算子 | 意味 | 例 |
---|---|---|
and | 両方の式が真だったらtrue | x > 2 and x < 10 |
or | 式のどちらか一方が真ならtrue | x > 3 or x < 2 |
not | 条件の反転。結果がTrueならFalseに反転する。 | not(x > 1 and x < 10) |
組み込みデータ型(Built-in Data Types)
代表的なものとして下記があります。
型名 | 意味 |
---|---|
int | 整数 |
float | 浮動小数点 |
str | 文字列 |
list | リスト |
tuple | タプル |
dict | 辞書 |
set | 集合 |
bool | 真偽値 |
int
>>> x = 20 >>> x 20 >>> type(x) <class 'int'>
float
>>> x = 0.25 >>> x 0.25 >>> type(x) <class 'float'>
str
シングルクオーテーションで定義
>>> s = 'abcdefg' >>> s 'abcdefg' >>> type(s) <class 'str'>
ダブルクオーテーションで定義
>>> s = "abcdefg" >>> s 'abcdefg' >>> type(s) <class 'str'> >>>
list
>>> l = [1, 5, 9, 12] >>> l [1, 5, 9, 12] >>> type(l) <class 'list'>
tuple
>>> x = (1, 'hoge', [1, 2, 3]) >>> x (1, 'hoge', [1, 2, 3]) >>> x[0] 1 >>> x[1] 'hoge' >>> x[2] [1, 2, 3] >>> x[2][2] 3 >>> type(x) <class 'tuple'>
set
>>> x = {'hoge', 'fuga', 'moge', 99} >>> x {'fuga', 99, 'moge', 'hoge'} >>> type(x) <class 'set'>
bool
>>> x = True >>> type(x) <class 'bool'> >>> x = False >>> x False >>> type(x) <class 'bool'>