Basic Python writing

Write a log of basic python cleanup.

data type

When calculated with int and float, it becomes a float type with a lot of information.

type(3+1.3)
> float

When writing decimal numbers such as 0,1 0.0001

1e-1
> 0.1 (10-1st power = 1/10= 0.1)
1e-3
>0.001

slice

'hello'[1:3]
>el

'fileid.png'[:-4]
>fileid
'fileid.png'[-4:]
>.png

Split into a list

'hello world'.split(' ')
>['hello' ,' world']

new line \Line break with n

Tuple list that cannot be changed

Set List with only unique values (infrequent)

set1 = {1,1,1,2,2,3,3,3}
> [1,2,3]

set () is often used to remove duplicate lists

list1 = [1,2,2,3,3,3,4,4,4,4]
set(list1)
> {1,2,3,4)

How to use is (~ and ~ are the same.)

#Compare variables
a = 1
b = 1
a is b
> True

#Compare lists (lists are treated differently because they compare different memory values)
a = [1,2]
b = [1,2]
a is b
> False
a is not b
> True

★ ~ is None, null object Noneno Most of the cases used for discrimination (when dealing with data)

When writing an if statement in one line ★ (Since it is difficult to understand, it is not often used except for the lambda function)

a = 3
print(' a is 2') if a == 2 else print('a is NOT 2')
> a is NOT 2

(Order) The process you want to execute first if ~ else Execution process

Use enumerate () when you want to use both index and element of list

for idx,color in enumerate(colors):
    favorite color = 'blue'
    if color == favorite color:
        print('{}:{} is my favorite color!'.format(idx,color))
    else:
        print('{}:{} is  not my favorite color...'.format(idx,color))

List comprehension ... Write a for statement in the list (convenient!) ★★

colors = ["red","blue","green",'yellow','white']
[color + '.png' for color in colors ]
> ['red.png', 'blue.png', 'green.png', 'yellow.png', 'white.png']

iterable and iterator

Determine if the object can iterate (iterate, loop).

iterable = repeatable object (object) ○ String,List,Tuple,Set,Dict ✖️ interger, Float, Boolean

Detailed definition iterable: An object that returns an Iterator with the iter () function iterator: Objects that can be iterated with the next () function

★ "Is it iterable?" → Can be turned with a for statement ・ ・ ・ ・ When it becomes difficult, it is important to be able to determine whether to return an iterator or an iterator. (Iterator is also Iterable)

function


Basic concept / operation
Parameters and Arguments

y = 3x (1 is an argument when x is a parameter x = 1)

_ (Underscore) The return value of the last executed code is stored.

If the function has no return value, it returns None. Ex function definition without return

p_r = print("hello world")
p_r
>
p_r is None
>True

★ A parameter with a default value cannot be placed before a parameter without a default value. Must be behind

def function_example( param1 = 'hello', param2):
>An error will occur

def function_example( param1 , param2 = 'hello'):
>Feasible

★ Convenient function ★ SHIFT + tab will display the contents (usage) of the function

mutable and immutable

Mutable         vs      Immutable Changeable object, non-changeable object list integer, stirng dict float, bool , tuple set

Mutable is passing the location of memory, not the value passed by reference (All Python is passed by reference)

In the case of an Immutable object, it behaves like passing by value.

fig-05.png

b64309a1-6425-9fd7-cf63-565cbd65a549.png

Why is it such a complicated mechanism ??

(Why are there mutable and Immutable?)

Objects (list, dict) that tend to have a large capacity are duplicated when passed from mutable to value, so the memory capacity becomes full immediately. So pass by reference

lambda function

In the case of a simple function that can be written in one line, use it as an anonymous function that does not need to be defined. Often used in spreadsheets

args and kwargs

def return_only_png(*args):
    
    png_list = []
    
    for filename in args:
        if filename[-4:] == '.png':
            png_list.append(filename)
        
    return png_list
  • args uses argument parameters as tuples. You can put as many elements as you like in * args. Names other than args are OK

  • Frequently use * args in parallel processing

** In the case of kwargs, receive it as a dictionary.

def print_dict(**kwargs):
    print(kwargs)

print_dict(a=1,b=2)
> {'a': 1, 'b': 2}

Recommended Posts