LoginSignup
2
2

More than 3 years have passed since last update.

Pythonの基本文法をJupyter Labで書いてみた

Last updated at Posted at 2020-04-14

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'
2
2
0

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
2
2