[원격 강의] 파이썬 문법 기초

우정·2022년 11월 8일
0

[내일배움캠프] TIL

목록 보기
2/50
  • 변수
    • 값을 담는 박스, 값을 가리키고 있는 것
    • 변수이름 = 값
    • 자료형
      • 숫자형
        a = 7  # 7을 a에 넣음
        b = 2  # 2를 b에 넣음
        
        print(a+b)
        
        a//b  # 3 (몫)
        a%b   # 1 (나머지)
        a**b  # 49 (거듭제곱)
      • 문자열
        a = 'woojeong'
        
        print(a)
      • bool 자료형
        a = True
        
        print(a)
        
        # 또 다른 예시
        a = (3 > 2)  # (3 < 2) 
        
        print(a)     # False
        # True
    • 문자열
      a = 2
      b = 'a' # 문자열 a(변수아님)
      
      print(b)
      __________________________________
      a = '2' # 문자열 2  # a = 2로 하고 똑같이 하면 에러가 남
      b = 'hello'
      
      print(a+b) #2hello
      # '2' = str(2)
      
      # str(): 문자열로 변환
      # len(): 길이
      
      # 문자열 자르기
      text = 'abcdefghijk'
      result = text[:3] # [:3] = ~3, [3:] = 4~, [3:8] = 4~8, [:] = 복사
      
      print(result)
      # sparta만 출력하고 싶을 때
      myemail = 'abc@sparta.co'
      result = myemail.split('@')[1].split('.')[0]
      
      print(result)
    • 리스트와 딕셔너리
      • 리스트 : 순서가 중요하게 값을 담는 것
        a_list = ['사과', '배', '감']
        
        print(a_list)
        
        # a_list.append() = 리스트 추가하는 방법
      • 딕셔너리 : key:value로 값을 담는 방법에 대한 자료형
        person = {"name":"Bob", "age": 21}
        print(person["name"])
        
        # 빈 딕셔너리 만들기
        a = {}
        a = dict()
      • 퀴즈
        • smith의 과학 점수를 출력해보자
          people = [
              {'name': 'bob', 'age': 20, 'score':{'math':90,'science':70}},
              {'name': 'carry', 'age': 38, 'score':{'math':40,'science':72}},
              {'name': 'smith', 'age': 28, 'score':{'math':80,'science':90}},
              {'name': 'john', 'age': 34, 'score':{'math':75,'science':100}}
          ]
          
          print(people[2]['score']['science'])
    • 조건문
      • if문
      • else와 elif
        money = 3000
        
        if money > 3800:
            print('택시를 타자!')
        elif money > 1200:
            print('버스를 타자')
        else:
            print('걸어가자')
    • 반복문
      • 기본 코드
        fruits = ['사과', '배', '감', '귤']
        
        for fruit in fruits:
            print(fruit) #리스트 안에 있는 요소들을 꺼내서 써 먹는 것
      • 응용 코드
        people = [
            {'name': 'bob', 'age': 20},
            {'name': 'carry', 'age': 38},
            {'name': 'john', 'age': 7},
            {'name': 'smith', 'age': 17},
            {'name': 'ben', 'age': 27},
            {'name': 'bobby', 'age': 57},
            {'name': 'red', 'age': 32},
            {'name': 'queen', 'age': 25}
        ]
        
        for person in people:
            name = person['name']
            age = person['age']
            if age > 20:
                print(name, age)
        for i, person in enumerate(people):
            name = person['name']
            age = person['age']
            print(i, name, age) # i = 순서를 정해줌(0~7)
            if i >3:
                break # 4 ben 27까지 출력됨
      • 연습문제
        # 짝수 출력하기
        num_list = [1, 2, 3, 6, 3, 2, 4, 5, 6, 2, 4]
            
        for num in num_list:
            if (num % 2) == 0:
                print(num)
            
        # 짝수의 개수를 출력하기
        count = 0
        for num in num_list:
            if (num % 2) == 0:
                count += 1
        print(count)
            
        # 리스트 안에 있는 모든 숫자 더하기
        sum = 0
        for num in num_list:
            sum += num
            
        print(sum)
            
        # 리스트 안에 있는 자연수 중에 가장 큰 숫자 구하기
        max = 0
        for num in num_list:
            if max < num:
                max = num
            
        print(max)
          
    • 함수
      def sum(a,b):
          return a+b 
          
      result = sum(1,2) # 3이 됨.
      print(result)
      def bus_rate(age):
          if age > 65:
              print('무료입니다')
          elif age > 20:
              print('성인입니다')
          else:
              print('청소년입니다')
          
      bus_rate(35) # 성인입니다
          
      -----------------------------
      def bus_fee(age):
      	if age > 65:
          	return 0
          elif age > 20:
              return 1200
          else:
          	return 0     
          
      money = bus_fee(28)
      print(money) # 1200
      • 퀴즈
        # 주민등록번호로 성별 출력하기
        def check_gender(pin):
            num = pin.split('-')[1][:1]
            if int(num) % 2 == 0:
                print('여성입니다')
            else:
                print('남성입니다')
        
        check_gender('150101-1012345')
        check_gender('150101-2012345')
        check_gender('150101-4012345')

파이썬 문법 심화

  • 튜플 (tuple)
    • 리스트랑 똑같이 생겼는데(순서가 있는 자료형) 불변형임.
    • 내용을 바꿀 수 없음
      # 오류!!!!
      a = ('사과','감','배')
      a[1] = '수박' # 바꿀 수가 없음
      print(a)
      
      # 이럴 때 주로 사용(딕셔너리 대신 비슷하게 만들어 사용할 때)
      a_dict = [('bob','24'),('john','29'),('smith','30')]
  • 집합 (set)
    • 중복을 걸러 준다.
      # a_set이라는 변수를 만들고, 리스트를 집합에다가 넣으면 집합이 만들어 짐.
      a = [1,2,3,4,3,2,3,4,5,8,7,1]
      a_set = set(a)
      print(a_set)
      
      # 중복을 제거해 줌
      {1, 2, 3, 4, 5, 7, 8}
    • 교집합 / 합집합 / 차집합도 구할 수 있음
      a = ['사과','감','배','수박','귤']
      b = ['배','사과','포도','참외','수박']
          
      a_set = set(a)
      b_set = set(b)
          
      print(a_set & b_set)  #교집합
      print(a_set | b_set)  #합집합
      student_a = ['물리2','국어','수학1','음악','화학1','화학2','체육']
      student_b = ['물리1','수학1','미술','화학2','체육']
          
      a_set = set(student_a)
      b_set = set(student_b)
          
      print(a_set - b_set)  # 차집합
          
      >> {'물리2', '음악', '화학1', '국어'}
        
  • f-string
    scores = [
        {'name':'영수','score':70},
        {'name':'영희','score':65},
        {'name':'기찬','score':75},
        {'name':'희수','score':23},
        {'name':'서경','score':99},
        {'name':'미주','score':100},
        {'name':'병태','score':32}
    ]
        
    for s in scores:
        name = s['name']
        score = s['score'] # str(s['score'])로 적어도 됨
        print(name+'의 점수는 '+str(score)+'점입니다.')  # score은 숫자이기 때문에 문자로 바꿔줘야 함.
        									           # 문자에서 숫자로 바꿀 때는 int()
            
        print(f'{name}의 점수는 {str(score)}점입니다.')  # 이렇게 해주는 게 훨씬 보기 좋음!
      
  • 예외처리
    • 서버한테 콜을 할 때 주로 사용.
    • 하지만 남용하면 돌아는 가는데 뭔가 이상해지고 무슨 에러가 났는지 모를 수가 있음.
    • 웬만하면 안 쓰길 권장
      people = [
          {'name': 'bob', 'age': 20},
          {'name': 'carry', 'age': 38},
          {'name': 'john', 'age': 7},
          {'name': 'smith', 'age': 17},
          {'name': 'ben', 'age': 27},
          {'name': 'bobby'},
          {'name': 'red', 'age': 32},
          {'name': 'queen', 'age': 25}
      ]
      
      for person in people:
          if person['age'] > 20:  
              print(person['name'])
      
      # 만약 bobby에 age가 없다면 에러가 남. 그럴 때 try-except를 사용하면 됨.
      for person in people:
          try:
              if person['age'] > 20:
                  print(person['name'])
          except:
              print(person['name'], '에러입니다')
  • 파일 불러오기

    • main_test.py
      from main_func import *  # main_func에 있는 함수들을 가져옴
      
      say_hi()
      say_hi_to('영수')
      --------------------------------
      from main_func import say_hi_to  # 원하는 것만 지정해서 가져올 수도 있음
      
      say_hi_to('영수')
    • main_func.py
      def say_hi():
          print('안녕!')
      
      def say_hi_to(name):
          print(f'{name}님 안녕하세요')
  • 한 줄의 마법

    • if문 - 삼항 연산자
      num = 3
          
      if num % 2 == 0:
      #     print('짝수')
          result = '짝수'
      else:
      #     print('홀수')
          result = '홀수'
          
      # print('3은 홀수입니다')
      print(f'{num}{result}입니다')
      # 간단하게 작성
      num = 3
          
      result = ('짝수' if num % 2 == 0 else '홀수')  # 괄호 없어도 됨
          
      print(f'{num}{result}입니다')
        
    • for문 - 한 방에 써버리기
      a_list = [1,3,2,5,1,2]
          
      # [2,6,4,10,2,4] 이렇게 만들고 싶을 때
          
      # b_list = []
      # for a in a_list:
      #     b_list.append(a*2)
          
      b_list = [a*2 for a in a_list]
          
      print(b_list)
  • map

    people = [
        {'name': 'bob', 'age': 20},
        {'name': 'carry', 'age': 38},
        {'name': 'john', 'age': 7},
        {'name': 'smith', 'age': 17},
        {'name': 'ben', 'age': 27},
        {'name': 'bobby', 'age': 57},
        {'name': 'red', 'age': 32},
        {'name': 'queen', 'age': 25}
    ]
        
    def check_adult(person):
        if person['age'] > 20:
            return '성인' # 2. 그 리턴 값을 모아서
        else:
            return '청소년'
        
    result = map(check_adult, people) # 1. people을 돌면서 하나하나를 check_adult에 넣은 것
    print(list(result)) # 3. 이렇게 리스트로 만듦
    # 간단하게 정리하는 방법
    def check_adult(person):
        return '성인' if person['age'] > 20 else '청소년'
        
    result = map(check_adult, people)
        
    print(list(result)) 
      
  • lamda

    • result = map(lambda x: x, people)
      result = map(lambda person: ('성인' if person['age'] > 20 else '청소년'), people)
      
      print(list(result))
  • filter

    • map과 유사하지만 True인 것들만 뽑혀오는 것
      result = filter(lambda x: x['age'] > 20, people)
      
      print(list(result))
  • 함수 심화(눈으로만 익혀두기)
    # 여긴 이미 배운 내용
    def cal(a,b):
        return a+2*b
       
    result = cal(1,2)
    print(result)
    result = cal(b=2,a=1) # 이런 식으로 지정할 수도 있음. 이 경우, 순서 안 맞춰도 됨.
    def cal(a,b=2): # 값을 정해주면
        return a+2*b
    
    result = cal(1) # 숫자 1 하나만 넣을 땐 a = 1이 되어 계산
    result = cal(1,3) # 1+2*3 = 7
    print(result)
    • *args : 변수를 무제한으로 넣을 수 있음
    • **kwargs : 키워드 인수를 여러 개 받는 방법
  • 클래스
    • 객체지향적 : 물체를 중앙이 아니라 자체적으로 관리하게 하는 것
    • 객체 : 물체 안에 관련된 속성들을 넣어두고 그것을 컨트롤 할 수 있는 함수들을 만들어 붙여주고, 가운데(중앙)에서는 해당 함수만 불러다가 그 물체를 제어하는 것
  • 느낀 점
    • 들여쓰기의 중요성!! 이거 하나로 값이 천차만별,,, 오류가 뜰 수도 있다!!
    • 어제 자바하다가 오늘 파이썬 하려니까 조금 헷갈린다.... 여긴 ;가 아니라 :를 써야하고,,,,,, 사소한 게 다르니까 더 헷갈리는 느낌,,, 그래도 파이썬 오늘 다 들었으니까..! 이제 자바에 집중하자 ~

0개의 댓글

관련 채용 정보