euisblue
파이썬 기초 정리
기본 자료형, 조건문, 반복문, 리스트, 함수, 람다식, 등등 정리  

    정수형 (Integer)

    1a = 2 2 b = 5 3 4 print(a+b) # 2+5 = 7 5 print(a*b) # 2*5 = 10 6 print(a**b) # 2^5 = 32 7 print(b**a) # 5^2 = 25 8 print(b%a) # 5%2 = 1 9 print(b//a) # 5/2 = 2

    실수형 (Float)

    1a = 2.5 2 b = 5. 3 c = a/b # 2.5 / 5.0 = 0.5 4 5 print(c) # 0.5 6 print(d) # 0

    문자열 (Strings)

    1str1 = 'hello' 2 str2 = "world" 3 4 print(str1) # hello 5 print(str2) # world 6 7 print(str1 + " " + str2) # hello world 8 9 print("{} {}".format(str1, str2)) # hello world 10 print("{a} {b}".format(a=str1, b="Blue")) # hello Blue 11 12 print("{} {a} {}".format(str1, str2, a="...")) # hello ... world

    문자열 자르기

    문자열[start:end) - start인덱스에서 end까지의 문자들을 가져온다.

    1s = "My_name_is_Blue" 2 3 print(s[0:]) # My_name_is_Blue 4 print(s[0:2]) # My 5 print(s[3:7]) # name

    리스트 (Lists)

    간단한 리스트 (1차원)

    1a = [1,2,3] 2 print(a) # [1, 2, 3] 3 print(a[0]) # 1 4 print(a[1]) # 2 5 6 a.append(4) 7 print(a) # [1, 2, 3, 4] 8 print(a[0:2]) # [1, 2]

    리스트의 리스트.. (n차원)

    1b = [1, [2, 3], 'hello'] 2 print(b[1]) # [2, 3] 3 print(b[1][0]) # 2 4 print(b[2]) # 'hello' 5 6 b[1] = 5 7 print(p) # [1, 5, 'hello'] 8 9 c = [1, [2, [3]]] 10 print(c[1]) # [2, [3]] 11 print(c[1][1]) # [3] 12 print(c[1][1][0]) # 3
    • 리스트는 mutable이므로 값의 변경이 가능하다.

    딕셔너리 (Dictionary)

    1d = { 2 'name': 'Blue', 3 'age' : 20, 4 'langs': ['en', 'ko'] 5 } 6 7 print(d) # {'name': 'Blue', 'age': 20, 'langs': ['en', 'ko'] } 8 print(d['name']) # 'Blue' 9 print(d['age']) # 20 10 print(d['langs']) # ['en', 'ko'] 11 print(d['langs'][0]) # 'en'

    불리언 (Boolean)

    1print(0 == 0) # True 2 print(0 == 1) # False 3 4 print(not True) # False 5 print(not False) # True

    참(True)과 거짓(False)을 나타내는 자료형.

    1age = 20 2 3 if(age == 20): 4 print("20살 입니다.") 5 else: 6 print("20살이 아닙니다.") 7 8 # 참이므로 '20살 입니다."를 출력

    튜플 (Tuples)

    1t = (1,2) 2 print(t) # (1, 2) 3 print(t[1]) # 2 4 5 t[0] = 3 # TypeError: 'tuple' object does not support item assignment
    • 튜플은 immutable이므로 값의 변경이 불가능하다.

    집합 (Sets)

    1days = {"monday, monday, tuesday, wednesday, tuesday"} 2 print(days) # {'wednesday', 'tuesday', 'monday'} 3 4 days.add('friday') 5 print(days) # {'wednesday', 'friday', 'tuesday', 'monday'}

    비교 연산자 (Comparison Operators)

    1print(1 < 2) # True 2 print(1 > 2) # False 3 print(2 <= 2) # True 4 print(2 >= 2) # True 5 6 print("abc" == "def") # False 7 print("abc" != "def") # True

    논리 연산자 (Logical Operators)

    • and는 조건이 모두 참이어야 True
    • or은 조건 중 하나만 참이면 True
    1print(True and True) # True 2 print(True and False) # False 3 4 print(True or True) # True 5 print(True or False) # True 6 print(False or False) # False

    조건문 (Coditional Statements)

    1score = 75 2 3if score >= 90: 4 printf("A") 5elif score >= 80: 6 printf("B") 7elif score >= 70: 8 print("C") 9elif score >= 60: 10 print("D") 11else: 12 print("Fail") 13 14# 'C'가 출력된다

    반복문 (Loops)

    for 반복문

    1colors = ["Blue", "Pink", "Purple"] 2 3for color in colors: 4 print(color) 5 6# Blue 7# Pink 8# Purple

    while 반복문

    1sum = 0 2num = 1 3while num < 101: 4 num += 1 5 sum += num 6 7print("1부토 100까지 더한 값은: {}".format(sum)) # 1부터 100까지 더한 값은: 5050

    range() 범위 지정

    1for i in range(0, 100): 2 print(i) 3 # 0, 1, 2, ..., 98, 99 4 5for i in range(0, 100, 2): 6 print(i) 7 # 0, 2, 4, ..., 94, 96, 98

    listrange()를 사용하여 원하는 범위의 리스트를 만들 수 있다.

    1list(range(10, 21)) # [10, 11, ...., 19, 20]

    함수 (Functions)

    짝수인지 홀수인지 판별해주는 함수

    1def isEven(number): 2 return number % 2 == 0 3 4print("2: {}".format(isEven(2))) # 2: True 5print("1: {}".format(isEven(1))) # 1: False 6print("0: {}".format(isEven(0))) # 0: True

    인사하는 함수. hello()함수를 인자 없이 호출하면 디폴트 값인 Blue가 출력된다.

    1def hello(name = "Blue"): 2 print("Hello {}".format(name)) 3 4hello() # Hello Blue 5hello('James') # Hello James

    람다식 (Lambda Expression)

    위에서 작성한 isEven(number)함수를 람다식으로 작성하면 아래와 같다.

    1def isEven(n): 2 return n % 2 == 0 3 4# lambda expression 5isEven = lambda n: n % 2 == 0

    람다식을 map 또는 filter와 같은 구조에 가져다 사용할 수 있다.

    맵 (Map)

    위에서 만든 람다식으로 0부터 10의 숫자들이 각각 짝수인지 홀수인지 확인해보자. 짝수면 True 홀수면 False이다.

    1isEven = lambda n: n % 2 == 0 2nums = list(range(0, 11)) # [0, 1, 2, ..., 8, 9, 10] 3 4list(map(isEven, nums)) # [True, False, True, ..., True, False, True]

    map에서 직접 람다식을 작성해도 된다.

    1list(map(lambda n: n*2, nums)) # [0, 2, 4, ..., 16, 18, 20]

    필터링 (Filter)

    map이 각 원소에 해당 람다식을 적용시킨 것이라면, filter는 람다식 조건에 부합하는 값들만 추려서 반환한다.

    1isEven = lambda n: n % 2 == 0 2nums = list(range(0, 11)) # [0, 1, 2, ..., 8, 9, 10] 3 4list(filter(isEven, nums)) # [0, 2, 4, 6, 8, 10] 5list(filter(lambda n: n > 5, nums)) # [6, 7, 8, 9, 10]