PYTHON 기초-1

jenna·2022년 11월 21일
0

PYTHON

목록 보기
2/2

1.Python 기초

1. 변수 선언과 자료형

a**b => a^b

a = (3 > 2)
print(a) => true

a = 2
b = a
print(b) => 2

2. 문자열 다루기

a = 2
b = 'a'
print(b) => a(문자열)

a = '2'
b = 'hello'
print(a + b) => '2hello'

a = 2
b = 'hello'
print(a + b) => TypeError: unsupported operand type(s) for +: 'int' and 'str'

  • 문자열 변환: str(2) => '2'
  • 문자열 길이: len(text) => 4
  • 문자열 자르기:
text = 'abcdefghijk'
result = text[3:8]
print(result) => 'defgh'

result = text[:]
print(result) => 'abcdefghijk'

text = 'abc@sparta.co'
result = myemail.split('@')[1].split('.')[0]
print(result) => sparta

text = 'sparta'
result = text[:3] => 앞에서 3개
print(result) => spa

phone = '02-123-1234'
(result = phone.split('-') => ['02', '123', '1234'])
result = phone.split('-')[0]
print(result) => 02

3. 리스트와 딕셔너리

리스트(list)

a_list = [2, '배', true]
print(a_list[0]) => 2

a_list = [2, '배', true, ['사과', '감']]
print(a_list[3]) => ['사과', '감']
print(a_list[3][1]) => 감

a_list.append(99)
print(a_list) => [2, '배', true, ['사과', '감'], 99]

a_list = [1,5,3,4,2]
result = a_list[-1]
print(result) => 2

a_list.sort() =>정렬하기
print(a_list) => [1,2,3,4,5]

a_list.sort(reverse=True)
print(a_list) => [5,4,3,2,1]

result = (5 in a_list) => a_list에 5가 있으며 true, 없으면 false
print(result) => true

딕셔너리(dictionary)

: 순서라는 개념이 없고 {key:value}형태

a_dict = {'name':'bob','age':27,'friend:['영희','철수']}

print(a_dict['name']) => bob

print(a_dict['age']) => 27

print(a_dict['friend']) => ['영희','철수']
print(a_dict['friend'][1]) => 철수

a_dict['height'] = 180
print(a_dict) => {'name':'bob','age':27,'friend:['영희','철수'], 'height': 180}

result = ('height' in a_dict)
print(result) => true

people = [
	{'name':'bob','age':27},
    {'name':'john','age':30}
]
print(people[1]) => {'name':'john','age':30}
print(people[1]['age']) => 30

Q1. smith의 science score

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']) => 90

4. 조건문

money = 5000

if money > 3800:
    print('택시를 타자!')  => 택시를 타자!
    
    
money = 3000

if money > 3800:
    print('택시를 타자!')
elif money > 1200:
    print('버스를 타자!')
else:
    print('걸어가자')  =>  버스를 타자!

5. 반복문

: 리스트 안에 있는 요소들을 하나씩 꺼내씀

fruits = ['사과','배','감','수박','딸기']

for fruit(지어준 변수이름, 마음대로 지으면 됨) in fruits:
    print(fruit) 

Q1. 나이 출력하기

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']
    print(name, age)
    
    =>bob 20
    carry 38
	john 7
	smith 17
	ben 27
	bobby 57
	red 32
    queen 25
    
for person in people:
    name = person['name']
    age = person['age']
    if age > 20:
        print(name, age)
        
        =>carry 38
		ben 27
		bobby 57
		red 32
		queen 25
        
for i, person in enumerate(people): #요소의 순서를 추가
    name = person['name']
    age = person['age']
    print(i, name, age)
    if i > 3:  #i가 3보다 크면 멈춰라 인데 i가 4일 때 if문 들어가기 전 이미 print가 되서 4까지 출력되고 if문 들어가서 판별 gn 3보다 커서 break
        break
        
        =>0 bob 20
		1 carry 38
		2 john 7
		3 smith 17
		4 ben 27

Q2. 짝수만 출력하는 함수

num_list = [1, 2, 3, 6, 3, 2, 4, 5, 6, 2, 4]

for num in num_list:
    if num % 2 == 0:
        print(num)

Q3. 짝수개 몇개인지

num_list = [1, 2, 3, 6, 3, 2, 4, 5, 6, 2, 4]

count = 0
for num in num_list:
    if num % 2 == 0:
        count += 1
print(count) => 7

Q4. 리스트 속 모든 숫자 더하기

num_list = [1, 2, 3, 6, 3, 2, 4, 5, 6, 2, 4]

sum = 0
for num in num_list:
    sum += num   #sum을 계속 num 만큼 증가 시켜라
print(sum) => 38

Q5. 리스트 속 자연수 중 가장 큰 숫자

num_list = [1, 2, 3, 6, 3, 2, 4, 5, 6, 2, 4]

max = 0
for num in num_list:
    if max < num:
        max = num
        # num1이 max0보다 크면
        # max의 값은 num값이 된다, max=1
        # num2가 max1보다 크면
        # max의 값은 num값이 된다, max=2
        # .
        # .
        # .
    
print(max) => 6

6. 함수

def (함수이름;)hello():
    print("안녕!")
    print("또 만나요!")
hello()

def sum(a,b):
    return a+b
result = sum(1,2)
print(result) => 3

def sum(a,b):
    print('더하기를 하셨네요!')
    return a+b
result = sum(1,2)
print(result) => 더하기를 하셨네요 3

def bus_rate(age):
    if age > 65:
        print('무료')
    elif age > 20:
        print('성인')
    else:
        print('청소년')
bus_rate(15) => 청소년

def bus_rate(age):
    if age > 65:
        return 0
    elif age > 20:
        return 1200
    else:
        return 750
myrate = bus_rate(17)
print(myrate) => 750

Q1. 주민등록번호 입력 받아 성별 알아보기

def check_gender(pin):
    num = pin.split('-')[1][:1] #-기준으로 나운 [1]첫번쨰 리스트에 [:1]첫번째 문자; 문자라 int 숫자형으로 바꿔줌
    if int(num) % 2 == 0:
        print('여자')
    else:
        print('남자')
check_gender('150101-1012345')
check_gender('150101-2012345')
check_gender('150101-4012345')

2.Python 심화

1. 튜플, 집합

: 튜플은 리스트와 비슷하지만 불변인 자료형(추가 삭제 변경 못 함);

a = (1,2,3)

python
a_dict = [('bob','24'),('john','29'),('smith','30')]

a = [1,2,3,4,5,3,4,2,1,2,4,2,3,1,4,1,5,1]
a_set = set(a) (set: 중복제거)
print(a_set) => {1,2,3,4,5}

a = ['사과','감','수박','참외','딸기']
b = ['사과','멜론','청포도','토마토','참외']
a_set = set(a)
b_set = set(b)
print(a_set & b_set) # &교집합
print(a_set | b_set) # | 합집합

Q1. A는 들었는데 b는 안 들은것(차집합)

student_a = ['물리2','국어','수학1','음악','화학1','화학2','체육']
student_b = ['물리1','수학1','미술','화학2','체육']

a_set = set(student_a) #??set을 왜 해주는건지
b_set = set(student_b)

print(a_set - b_set) => {'국어', '음악', '화학1', '물리2'}

2. 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']
    print(name+'의 점수는 '+str(score)+'점입니다.')
    
    print(f'{name}의 점수는 {score}점입니다.')
    
    =>영수의 점수는 70점입니다.
      영희의 점수는 65점입니다.
      기찬의 점수는 75점입니다.
      희수의 점수는 23점입니다.
      서경의 점수는 99점입니다.
      미주의 점수는 100점입니다.
      병태의 점수는 32점입니다.

3. 예외처리

:중간에 에러가 나도 꺼지지 말고 에러표시 후 계속 진행
(안 쓰는게 좋음)

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:
    try:
        if person['age'] > 20:
            print(person['name'])
    except:
        print(person['name'], '에러입니다')

        =>carry
          ben
          bobby 에러입니다
          red
          queen

4. 파일 불러오기

:다른 파일에 있는 함수를 가져다 씀

  • main_test.py
#main_func file에 있는 함수를 가져다 쓰고 싶을 떄
from main_func import *  #main_func에 있는 함수들을 다 가져옴
#from main_func import say_hi_to #say_hi_to 함수만 가져올 때

say_hi()
say_hi_to('미미')
  • main_func.py
def say_hi():
    print('안녕')

def say_hi_to(name):
    print(f'{name}님 안녕하세요')

5. 한줄에 줄여쓰기

*if문
num = 3

#if num % 2 == 0:
#     result = '짝수'
#else:
#     result = '홀수'  =
     
result = ('짝수' if num % 2 == 0 else '홀수')
# (괄호 없어도 됨) result = '짝수' if num % 2 == 0 else '홀수'
*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)

6. map, filter, lambda식

  • map
  • lambda: ex)lambda x: x['age'] > 20
    * x라고 자주 쓰임
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}
]

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

print(list(result))


# def check_adult(person):
#     if person['age'] > 20:
#         return '성인'
#     else:
#         return '청소년'
# #== return '성인' if person['age'] > 20 else '청소년'
#
# result = map(check_adult, people)
# #people를 하나하나 돌면서 check_adult에 넣고

# result = map(lambda person: ('성인' if person['age'] > 20 else '청소년'), people)
# #people이 하나씩 돌면서 person에 넣을건데 그 person을 가지고 ('성인' if person['age'] > 20 else '청소년') 이렇게 return 해라

# print(list(result))
# #그 결과값을 다시 list로 묶는것
  • filter: map과 유사한데 true인것만
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}
]

result = filter(lambda x: x['age'] > 20, people)
#people의 요소를 x에 하나씩 넣고 그 x의 age값이 20보다 크면 걔네들만 취해라

print(list(result))

7. 함수 심화

  1. 함수에 인수를 넣을 때, 어떤 매개변수에 어떤 값을 넣을지 정해줄 수 있어요. 순서 상관 없음
def cal(a, b):
    return a + 2 * b

print(cal(3, 5))
print(cal(5, 3))
print(cal(a=3, b=5))
print(cal(b=5, a=3))
  1. 특정 매개변수에 디폴트 값을 지정해줄 수 있어요.
def cal2(a, b=3):
    return a + 2 * b

print(cal2(4))
print(cal2(4, 2))
print(cal2(a=6))
print(cal2(a=1, b=7))
  1. 입력값의 개수를 지정하지 않고 모두 받는 방법
def call_names(*args):
    for name in args:
        print(f'{name}야 밥먹어라~')

call_names('철수','영수','희재')
=> 철수야 밥먹어라~
	영희야 밥먹어라~
    희재야 밥먹어라~
  1. 키워드 인수를 여러 개 받는 방법(딕셔너리화 해줌)
def get_kwargs(**kwargs):
    print(kwargs)

get_kwargs(name='bob') => {'name':'bob'}
get_kwargs(name='john', age='27') => {'name':'bob', 'age':'27')}

8. 클래스

:물체에다가 물체에 관련된 속성들을 넣어두고 컨트롤할 수 있는 함수들을 만들어서 붙여주고 가운데(중앙)에서는 그 함수만 불러다가 그 물체를 제어하는 것들

class Monster(): #100hp를 가지고 있는 몬스터가 있가 있는데
    hp = 100
    alive = True

    def damage(self, attack):  #데미지라는 함수
        self.hp = self.hp - attack #공격받을 수록 깍이는 hp
        if self.hp < 0: #만약에 hp가 0보다 작다면
            self.alive = False #죽은것

    def status_check(self): #죽었는지 살았는지 체크해줌
        if self.alive: #기본적으로 self.alive == True
            print('살았다')
        else:
            print('죽었다')

m1 = Monster() #몬스터 한마리 라고 생각하면 편한데 (몬스터 한마리)m1은 인스턴스 개념이다/ Monster은 클래스
m1.damage(150) #데미지 150 줌
m1.status_check() #생사확인

m2 = Monster()
m2.damage(90) #데미지 150 줌
m2.status_check() #생사확인
profile
https://github.com/jennaaaaaaaaa

0개의 댓글