
수업 목표: 빠르게 기초 문법을 배운 뒤 사용해보기
notion_link
a = (3 == 2)
print(a)
#변수는 값을 담는 박스다 == 값을 가르키고 있다.
a = 3
b = 2
#3이라는 숫자가 a라는 박스에 들어갔다!
print(a/b)
문자열 2와 숫자 2는 다르다!
숫자 2를 문자열 2로 바꾸는 방법?
a ='2'
b = str(2)
print(a+b)
#출력 22
text = 'abcdefg'
result = text[3:]
print(result)
#출력:
앞으로 뒤로 중간 다 잘라봐라
myemail = "giwoonlee17@gmail.com"
result = myemail.split('@')[1].split('.')[1]
print(result)
#출력: com
표현: [리스트]로 표현
a_list = [2, '배', False, ['감','사과']]
print(a_list[3][1])
#출력: '감'
a_list = [1,3,4,5,678,8,7]
result = (678 in a_list)
print(result)
#출력: true
표현: {딕셔너리}로 표현, 순서가 없다!
a_dict = {'칠전팔기':['권지호','서준영','이기운','홍다윤'], '12조':['a','b','bd','cds'], 'managers':"there'sNoNeedToBeInATeam"}
print(a_dict['칠전팔기'][2])
# 출력: 이기운
# dictionary의 구조, print문의 구성(특히 '[]'의 위치와 쓰임새를 잘 숙지해야 할 것으로 보인다)
a_dict = {'칠전팔기':['권지호','서준영','이기운','홍다윤'], '12조':['a','b','bd','cds'], 'managers':"there'sNoNeedToBeInATeam"}
a_dict['peter'] = "james's father" #append a new dictionary
inspection = ('peter' in a_dict) # is 'peter' in dictionary?
print(inspection) # in 을 통해 'peter' 가 a_dict 안에 존재하는지 검증한다.
print(a_dict['peter']) #key 에 해당하는 value: "james's father" 을 출력한다.
people = [
{'name':'bob', 'age':27},
{'name':'john', 'age':30}
]
print(people[1]['age'])
# mission: "print out science score of 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'])
들여쓰기, 줄 맞춤은 필수
ex) if, elif, else 를 사용한 조건문 코드 작성 (feat. 군인재획득부서)
#장교가 되고 싶은 james, 그의 나이는 만27살이다. 입대가 가능할까?
age = 15
if 19 < age <= 27:
print("장교교육대에 오신걸 환영합니다.")
elif age < 19:
print("1년 뒤에 뵙겠습니다.")
print("학사 학위를 준비하세요")
else:
print(input("군필이신가요?"))
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}
]
# 20살 이상만 출력하라
for individual in people: #individual 말고도 어떤 것이든 올 수 있다.
name = individual['name'] # key 값(name)에 해당하는 value 값(bob,carry ..)들로 구성된 리스트 뽑아내기
age = individual['age'] # key 값(age)에 해당하는 value 값(20, 38 ..)들로 구성된 리스트 뽑아내기
if age > 20:
print(name, ":", age)
for i, person in enumerate(people):
name = = individual['name']
age = individual['age']
print(i, name, age)
if i > 2: #0,1,2 즉 상위 3개 까지만 출력하고 for 문을 break한다.
break
num_list = [1, 2, 3, 6, 3, 2, 4, 5, 6, 2, 4]
for num in num_list:
if num % 2 == 0:
print(num)
num_list = [1, 2, 3, 6, 3, 2, 4, 5, 6, 2, 4]
count = 0
for i in num_list:
if i % 2 == 0:
count = count + 1 # count += 1 과 같은 말이다.
print(count) # 최종 print 함수는 for 문 바깥에서 실행해야 한다. 한그러면 1부터 7까지 출력됨.
num_list = [1, 2, 3, 6, 3, 2, 4, 5, 6, 2, 4]
sum = 0
for num in num_list:
sum = sum + num
print(sum)
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 # 요놈이 포인드. 조건에 해당할 때 목표로 하는 출력 변수로 값을 배정해버린다.
print(max)
return : 변신주문
def sum(a, b):
return a + b
result = sum(1, 4) #return 1 + 4로 변신!
print(result)
def check_gender(pin):
print('')
my_pin = '200101-3012345'
check_gender(my_pin)
def check_gender():
if int(my_pin.split('-')[1][0]) % 2 == 0:
print("여자입니다")
else:
print("남자입니다.")
my_pin = '200101-3012345'
my_pin = '200101-1012345'
my_pin = '200101-2012345'
check_gender(my_pin)
def check_gender(pin):
num = pin.split('-')[1][:1]
if int(num) % 2 == 0: # 문자열 -> 숫자열 변환 by int()
print('여성')
else:
print('남성')
check_gender('200101-1012345')
check_gender('200101-2012345')
check_gender('200101-4012345')
# 리스트: a[1]로 리스트 구성을 바꿀 수 있음.
a = ['apple','persimmon', 'pear']
a[1] = 'watermelon'
print(a)
# 튜플: a[1]로 튜플을 바꿀 수 없음. typeError 발생
a = ('apple','persimmon', 'pear')
print(a)
a = ['사과','감','수박','참외','딸기']
b = ['사과','멜론','청포도','토마토','참외']
a_set = set(a)
b_set = set(b)
print(a_set & b_set) # 교집합
print(a_set | b_set) # 합집합
print(a_set - b_set) # 교집합 1
print(b_set - a_set) # 교집합 2
#집합 a, b가 [], {}, () 이어도 전부 set()을 통해 집합화 가능하다
scores = [
{'name':'영수','score':70},
{'name':'영희','score':65},
{'name':'기찬','score':75},
{'name':'희수','score':23},
{'name':'서경','score':99},
{'name':'미주','score':100},
{'name':'병태','score':32}
]
# 위 코드가 "딕셔너리들의 리스트" 이기 때문에 scores['name']으로 direct 접근이 불가하다.
# you need to iterate through the list to access each dictionary, or specify the index of the dictionary you want to access.
노트:
위 list는 말 그대로 여러개의 dict으로 구성되어 있다.
따라서 여기서 값을 뽑고 싶다면 그 방법은 다음과 같다.
1. iteration 활용
for i in scores:
name = i['name']
score = i['score']
print(name, score)
2. 목표 dict과 목표 valued의 key 값을 모두 제시
print(scores[0]['name'])
# '영수' 출력
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(f'{name}의 점수는 {score}점 입니다.')
# 위 코드가 "딕셔너리들의 리스트" 이기 때문에 scores['name']으로 direct 접근이 불가하다.
# you need to iterate through the list to access each dictionary, or specify the index of the dictionary you want to access.
기억하자!
a list of dictionaries 에서 원하는 value를 출력하려면,
1. for반복문을 사용하거나
2. print(scores[0]['name']) 처럼 원하는 value 값에 대응되는 key 값 좌표를 설정해줘야 한다.
트라이 해보고 없으면 exept를 실행해라~
남용하면 어디서 에러가 났는지 알 수 없게 된다.
people = [
{'name': 'bob', 'age': 20},
{'name': 'carry', 'age': 38},
{'name': 'john', 'age': 7},
{'name': 'smith', 'age': 17},
{'name': 'ben', 'age': 17},
{'name': 'bobby', },
{'name': 'red', 'age': 32},
{'name': 'queen', 'age': 25}
]
for person in people:
name = person['name']
if person['age'] > 20:
print(f"{name}은 성인입니다.")
KeyError: 'age'
이 때 값이 없는 부분만 체크하고 나머지 값을 출력하도록 하는 것이 try-exept 문 이다.
for person in people:
try:
name = person['name']
if person['age'] > 20:
print(f"{name}은 성인입니다.")
except:
name = person['name']
print(f"{name} - error")
출력값
carry은 성인입니다.
bobby - error
red은 성인입니다.
queen은 성인입니다.
from 파일이름 import *
say_hi()
"파일이름"에 있는 함수를 전부 가져다 쓸 수 있다.
map 리스트의 모든 원소 조작
filter 리스트의 모든 원소 중 특별한 것만 뽑기
함수의 인자