a = 7 # 7을 a에 넣음
b = 2 # 2를 b에 넣음
print(a+b)
a//b # 3 (몫)
a%b # 1 (나머지)
a**b # 49 (거듭제곱)
a = 'woojeong'
print(a)
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() = 리스트 추가하는 방법
person = {"name":"Bob", "age": 21}
print(person["name"])
# 빈 딕셔너리 만들기
a = {}
a = dict()
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'])
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')
파이썬 문법 심화
# 오류!!!!
a = ('사과','감','배')
a[1] = '수박' # 바꿀 수가 없음
print(a)
# 이럴 때 주로 사용(딕셔너리 대신 비슷하게 만들어 사용할 때)
a_dict = [('bob','24'),('john','29'),('smith','30')]
# 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', '국어'}
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'], '에러입니다')
파일 불러오기
from main_func import * # main_func에 있는 함수들을 가져옴
say_hi()
say_hi_to('영수')
--------------------------------
from main_func import say_hi_to # 원하는 것만 지정해서 가져올 수도 있음
say_hi_to('영수')
def say_hi():
print('안녕!')
def say_hi_to(name):
print(f'{name}님 안녕하세요')
한 줄의 마법
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}입니다')
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
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)