# clean python code

https://youtu.be/BrAsVWRHoL0?si=vy73AtUVNcdH6fZE

## Avoid full for loops

#=== User filter Function
# Avoid full for loops with filter function
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

def is_even(n):
return n % 2 == 0

def is_multiple3(n):#=== User filter Function (iterable object에 function을 적용하여 True인 값만 반환)
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
def is_even(n):
return n % 2 == 0
def is_multi3(n):
return n % 3 == 0

result = list(filter(is_even, numbers))   # [2, 4, 6, 8, 10]
result = list(filter(is_multi3, numbers)) # [3, 6, 9]

#=== Using map function (iterable object에 function을 모두 적용하여 반환)
def square(n):
return n * n
squared_numbers = list(map(square, numbers))    # [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

#=== Using lambda function (anonymous function를 간단히 사용)
result = list(filter(lambda n: n % 2 == 0, numbers))
result = list(filter(lambda n: n % 3 == 0, numbers))
squared_numbers = list(map(lambda n: n * n, numbers))

num1 = 5
num2 = 10
def add_nums(x, y):
return x + y
result = add_nums(num1, num2)

add_nums2 = lambda x, y: x + y
result = add_nums2(num1, num2)
return n % 3 == 0

evens = list(filter(is_even, numbers))          # [2, 4, 6, 8, 10]
multiples3 = list(filter(is_multiple3, numbers))# [3, 6, 9]

## underscore numbers & format numbers in formatted strings

### 1_000_000 == 1000000
num1 = 100_000_000_000
num2 = 100_000_000.123456
print(f'{num1:,}')   # 100,000,000,000
print(f'{num2:,.2f}')# 100,000,000.12
print(f'{num1+num2}')# 100100000000.12346

Categories: Python Basic

#### onesixx

Blog Owner

Subscribe
Notify of

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x