英文学生の日常

業務日誌.tomo

業務で感じたことをひたすら綴る

Jupyter Notebookを使ってPythonの基本文法をまとめた

Pythonの基本文法

3+3
6
3-2
4*5
6/2
7%2 #最後に実行された行の返り値のみ
1
type(1)
int
type(1.0)
float
type(3.14)
float
type('string')
str
'hello'[2]
'l'
'hello'[1:3]
'el'
'hello{}'.format('world')
'helloworld'
print('{one}{two}'.format(one='hello', two='world'))
helloworld

List

list_out = [1,2,'three']
list_out
[1, 2, 'three']

list_in = ['one', 'two', 3] list_out.append(list_in) print(list_out)

list_out[1]
2
list_out[3][1]
'two'
list_out = [1,2,'three']

Dictionary

dict = {'key1':'value1', 'key2':2}
dict['key1']
'value1'
dict = {'key1':[1,2,'value1']}
dict['key1'][2]
'value1'
dict = {'key_out':{'key_in':'value_in'}}
dict['key_out']
{'key_in': 'value_in'}
dict = {'key1':'value2', 'key2':2}
dict['key3'] = 'new_value'
dict
{'key1': 'value2', 'key2': 2, 'key3': 'new_value'}

Tuples

list1 = [1,2,3,4,5]
tuple1 = (1,2,3,4,5,6)
list1
[1, 2, 3, 4, 5]
tuple1
(1, 2, 3, 4, 5, 6)
list1[1] = 10 #listは変更可
list1
[1, 10, 3, 4, 5]
tuple1[1] = 10 #tupleは変更不可
---------------------------------------------------------------------------

TypeError                                 Traceback (most recent call last)

<ipython-input-38-df5023792f06> in <module>
----> 1 tuple1[1] = 10 #tupleは変更不可


TypeError: 'tuple' object does not support item assignment

関数

result_list=[] #頻出
for i in range(0,4):
    result_list.append(i*10)
result_list
[0, 10, 20, 30]
[i*10 for i in range(0,4)]
[0, 10, 20, 30]
i=0
while i<5:
    print('{} is less than 10'.format(i))
    i+=1
0 is less than 10
1 is less than 10
2 is less than 10
3 is less than 10
4 is less than 10

lambda関数

def function_name (param1, param2):
    print('Do something for {} and {}.format(param1, param2)')
    
    return 'param1' + 'and' + 'param2' 
param1 = 'something1'
param2 = 'something2'
output = function_name(param1, param2)
Do something for {} and {}.format(param1, param2)
def get_filename (path):
    return path.split('/')[-1]
get_filename('/home/school/pet/corona')
'corona'
lambda path: path.split('/')[-1]
<function __main__.<lambda>(path)>
x = lambda path: path.split('/')[-1]
x('/home/school/pet/corona')
'corona'