[Upstage AI Lab] python basics

who_am_I·2024년 4월 4일

[Upstage AI Lab]

목록 보기
2/19

수업에서 python data type 부터 반복문, 함수, class 에 대한 파이썬 기초들을 훑어보았다.
헷갈렸던 부분이나 잘 몰랐던 부분들을 정리해보았다.

print(f"{}")

String 다룰 때, print(f)가 헷갈렸는데 이번에 정리하면서 명쾌해졌다

name = 'velog'
age = 30

print("Name : " + name +", Age: " + str(age))
print("Name : {}, Age: {}".format(name, age)) # format
print(f"Name : {name}, Age: {age}")

print(f" {} " ) "" 안에서 {}는 변수로 인식한다
그래서 {} 외에는 다 string으로 써지니 str과 int를 혼합할 때, 굉장히 편하다

문자열 함수

  • strip() : 공백제거
a = "         파이썬은 쉽다       "
text = a.strip() # 공백제거 

output : 파이썬은 쉽다
  • join() : list를 str로
# 2) join()
words = ['안녕','하세요','파이썬']
sentence = "-".join(words)

output : 안녕-하세요-파이썬
  • split() : str을 list로
sentence.split('-')

output : ['안녕', '하세요', '파이썬']

Tuple

Tuple 의 가장 큰 특징은 한번 생성되면 값 변경이 불가능하다는 것
요소를 더하거나, 제거하거나, 수정하거나 X

하지만 다른 두 tuple을 concatenate은 가능!

a = (1,2,3,4,5)
new_a = a + (10, )  

output : (1,2,3,4,5,10) 

Dictionary

# { } 안에 key:value => {key:value, key2:value2 .. } 
# API 형태

x = {"name":"velog", "age":[30, 31], "city":"seoul"}
# dict안에 list도 가능

x['city']
output : 'seoul'

x.get('ages', 0) # x['age'] 보다 오류를 피하는 방법, ages가 없으면 0을 return
output : 0

new_name = {'name': 'leo'}
x.update(new_name) # value 바꾸기
output : {"name":"leo", "age":[30, 31], "city":"seoul"}

제어문

  • continue
for i in range(10):
    if 3<= i <= 5:
        print("조건문 i : ", i)
        continue # 다음 코드 무시

    print(i)
    
output : 

0
1
2
조건문 i :  3
조건문 i :  4
조건문 i :  5
6
7
8
9
  • break
for i in range(10):
    if 3<= i <= 5:
        print("조건문 i : ", i)
        break

    print(i)

output : 

0
1
2
조건문 i :  3

class

  • Constructor(생성자) : 처음 만들기 위해 속성을 초기화
  • Method : class 내의 함수
  • Instance : 호출시 만들어지는 객체
class FishBread: # Camel Case
    # 초기화 => 생성자 => 클래스가 호출됐을 때 가장 먼저 실행되는 함수(메소드)
    def __init__(self, name, ingredient):
        self.name = name
        self.ingredient = ingredient

    def bread(self):
        print(f"붕어빵의 이름은 {self.name}, 재료는 {self.ingredient}")

redbean_bread = FishBread('팥붕어빵', '팥')

redbean_bread.name
redbean_bread.ingredient
redbean_bread.bread()

생성자가 왜 필요한걸까 항상 의문이었는데, 새로운 instance를 만들기 위해서 필요함, self는 method에서 변수를 활용하기 위해 필요함!

profile
Data, AI

0개의 댓글