読者です 読者をやめる 読者になる 読者になる

技術ブログを目指すブログ

toncrimentan_w’s blog

pythonの基本の構文

python

基本の文法の学び方は

適当な本を本屋さんで買ってきて

教科書通りにコマンドを打っていきます。

 

慣れ親しんだC++とちがいリスト、タプル、ディクショナリなどの

書き方もあるのでまずは一行で書いていき学びます。

f:id:toncrimentan_w:20170130022610j:plain

f:id:toncrimentan_w:20170130022611j:plain

 

以下実験結果

 

Python 3.6.0 (v3.6.0:41df79263a11, Dec 23 2016, 07:18:10) [MSC v.1900 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> False
False
>>> 0.5
0.5
>>> "Hello"
'Hello'
>>> 'こんにちは'
'こんにちは'
>>> 1
1
>>> +1
1
>>> -10
-10
>>> 2-3
-1
>>> 2*3
6
>>> 6/3
2.0
>>> 2**3
8
>>> 8/6
1.3333333333333333
>>> 8//6
1
>>> 8%6
2
>>> 0.99
0.99
>>> 0.99999999999999999999999999999
1.0
>>> 2+3*4
14
>>> (2+3)*4
20
>>> "Hello'"+"World"
"Hello'World"
>>> "a"*3
'aaa'
>>> "Hello"*2
'HelloHello'
>>> a = 1
>>> b = 2
>>> c = 3
>>> a
1
>>> b
2
>>> c
3
>>> a+b+c
6
>>> bool 0
  File "<stdin>", line 1
    bool 0
         ^
SyntaxError: invalid syntax
>>> bool(0)
False
>>> bool(-1)
True
>>> bool("aaaaa")
True
>>> 2<3
True
>>> 2==3
False
>>> 2<=3
True
>>> 'ab'=='a'+'b'
True
>>> 'a' < 'b'
True
>>> '0' < '10'
True
>>> '1' < '10'
True
>>> '2' < '10'
False
>>> True and True
True
>>> True and False
False
>>> True or False
True
>>> not False
True
>>> not True
False
>>> not 1
False
>>> not 0
True
>>> '' or 'a'
'a'
>>> 0 or 100
100
>>> 100 or 10
100
>>> a = 1
>>> b = 2
>>> c = 3
>>> a and b or c
2
>>> a = 10
>>> if a < 0:
...     a = a * -1
... a
...
>>> a
10
Python 3.6.0 (v3.6.0:41df79263a11, Dec 23 2016, 07:18:10) [MSC v.1900 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> a = 1
>>> b = 2
>>> c = 3
>>> a and b or c
2
>>> a = 10
>>> if a < 0:
...     a = a * -1
... a
  File "<stdin>", line 3
    a
    ^
SyntaxError: invalid syntax
>>>
>>> a
10
>>> if a < 0:
...     a = a *1
...
>>> a
10
>>> a = 10
>>> if a < 0:
...     a = a * -1
... else:
...     a = a *10
...
>>> a
100
>>> a = -10
>>> b = 10
>>> if a > 0:
...     b = 1
... elif a == 0:
...     b = 0
... else:
...     b = -1
...
>>> b
-1
>>> i = 1
>>> while i < 10:
...     print(i)
...     i += 1
...
1
2
3
4
5
6
7
8
9
>>>
>>> i = 1
>>> while True:
...     print(i)
...     i += 1
...     if i > 10:
...             break

>>> l = [1,2,3,1]
>>> len(l)
4
>>> l +l
[1, 2, 3, 1, 1, 2, 3, 1]
>>>
>>> t = (1,2,3,1)
>>> t = 1,2,3,1
>>> len(t)
4
>>> t + t
(1, 2, 3, 1, 1, 2, 3, 1)
>>> t = 1,
>>> t
(1,)
>>> t = (2,)
>>> t
(2,)
>>> s = {1,2,3,1}
>>> s
{1, 2, 3}
>>> len(s)
3
>>> d = {'a':1, 'b':2, 'c':3, 'd':1}
>>> d
{'a': 1, 'b': 2, 'c': 3, 'd': 1}
>>> d['a'] = 4
>>> d
{'a': 4, 'b': 2, 'c': 3, 'd': 1}
>>> l = [1,2,3,4]
>>> 2 in l
True
>>>


>>> d = {'a':1, 'b':2}
>>> 'a' in d
True
>>> 1 in d
False
>>> 2 in d
False
>>> 'b' in d
True
>>> l = [1,2,3,4]
>>> 2 not in l
False
>>> 5 not in l
True

>>> l = [1,2,3,4,5,6,7,8,9]
>>> l[4:8]
[5, 6, 7, 8]
>>>