본문 바로가기

Programming

[Python][문법] 기초 - 3. 연산자_흐름제어

반응형
#!/usr/bin/env python
# coding: utf-8

# # 1. 연산자

# ### 1.1 수치 연산자

# In[ ]:


2 + 3


# In[ ]:


3 - 2


# In[ ]:


2 * 3


# In[ ]:


5 / 2


# In[ ]:


5 // 2


# In[ ]:


5 % 2


# In[ ]:


3.14 ** 2


# In[ ]:


2 ** 0.5


# In[ ]:





# ### 1.2 대입 연산자

# In[ ]:


a = 20


# In[ ]:


a += 5
a


# In[ ]:


a -= 10
a


# In[ ]:


a *= 2
a


# In[ ]:


a /= 3
a


# In[ ]:


a = 3
b = 2
a *= 2 + b    # a = a * ( 2 + b )
a


# In[ ]:





# ### 1.3 비교 연산자

# In[ ]:


a = 95


# In[ ]:


a == 90


# In[ ]:


a != 90


# In[ ]:


a > 90


# In[ ]:


a < 90


# In[ ]:


a >= 90


# In[ ]:


a <= 90


# In[ ]:


a >= 90 and a <= 100


# In[ ]:


90 <= a <= 100


# In[ ]:


100 <= a <= 110


# In[ ]:


70 <= a <= 80


# In[ ]:


lst1 = [1,2,'Hello World']
lst2 = [1,2,'Hello World']


# In[ ]:


id(lst1) == id(lst2)


# In[ ]:


lst1 == lst2


# In[ ]:


lst1 != lst2


# In[ ]:





# ### 1.4 논리 연산자

# In[ ]:


True and False


# In[ ]:


True or False


# In[ ]:


not True


# In[ ]:





# ### 1.5 식별 연산자

# In[ ]:


lst1 = [1,2,'Hello World']
lst2 = [1,2,'Hello World']


# In[ ]:


lst1 is lst2


# In[ ]:


lst1 is not lst2


# In[ ]:


lst1 == lst2


# In[ ]:


id(lst1) == id(lst2)


# In[ ]:





# ### 1.6 구성원 연산자

# In[ ]:


lst = [1,2,'Hello World']


# In[ ]:


1 in lst


# In[ ]:


3 not in lst


# In[ ]:


dic = {'a':1, 'b':2, 'c':3 }


# In[ ]:


'a' in dic


# In[ ]:


'k' in dic


# In[ ]:


1 in dic


# In[ ]:





# ### 1.7 연산자 활용

# In[ ]:


students = [
               {'num':'1','name':'김철수','kor':90,'eng':80,'math':85,'total':0,'avg':0.0,'order':0 },
               {'num':'2','name':'박제동','kor':90,'eng':85,'math':90,'total':0,'avg':0.0,'order':0 },
               {'num':'3','name':'홍길동','kor':80,'eng':80,'math':80,'total':0,'avg':0.0,'order':0 }
           ]


# In[ ]:


# 학생별 합계 구하기
students[0]['total'] = students[0]['kor'] + students[0]['eng'] + students[0]['math']
students[1]['total'] = students[1]['kor'] + students[1]['eng'] + students[1]['math']
students[2]['total'] = students[2]['kor'] + students[2]['eng'] + students[2]['math']


# In[ ]:


print(students[0]['total'])
print(students[1]['total'])
print(students[2]['total'])


# In[ ]:


# 학생별 평균 구하기
students[0]['avg'] = students[0]['total'] / 3
students[1]['avg'] = students[1]['total'] / 3
students[2]['avg'] = students[2]['total'] / 3


# In[ ]:


print(students[0]['avg'])
print(students[1]['avg'])
print(students[2]['avg'])


# In[ ]:


# 학급 평균 구하기
class_avg = (students[0]['total'] + students[1]['total'] + students[2]['total']) / 3


# In[ ]:


print(class_avg)


# In[ ]:


# 과목별 평균 구하기
kor_avg  = (students[0]['kor']  + students[1]['kor']  + students[2]['kor'])  / 3
eng_avg  = (students[0]['eng']  + students[1]['eng']  + students[2]['eng'])  / 3
math_avg = (students[0]['math'] + students[1]['math'] + students[2]['math']) / 3


# In[ ]:


print(kor_avg)
print(eng_avg)
print(math_avg)


# #### <참고> 연산자 우선순위

# In[ ]:


1 + 2 * 3 / 4


# In[ ]:





# ---

# # 2. 흐름 제어

# ### 2.1 흐름과 흐름 제어

# In[ ]:


print('Hello World')
print(1 + 2)
print('안녕하세요 파이썬')
print('흐름과 흐름 제어 입니다')


# ### 2.2 선택 흐름과 if 문

# #### if 문만 있는 경우

# In[ ]:


grade = float(input('총 평점을 입력해 주세요: '))

if grade >= 4.3:
    print('당신은 장학금 수여 대상자 입니다.')
    print('축하합니다.')

print('공부 열심히 하세요.')


# #### if else 문

# In[ ]:


data = int(input('숫자를 입력하시오: '))

if data % 2 == 0:
    print('입력된 값은 짝수입니다.')
else:
    print('입력된 값은 홀수입니다.')


# In[ ]:


score = int(input('점수를 입력하시오: '))

if score >= 70:
    print('당신은 시험을 통과했습니다.')
else:
    print('당신은 시험을 통과하지 못했습니다.')
   
print('공부 열심히 하세요!')


# #### 중첩된 if ~ else ~ 구문

# In[ ]:


age = int(input('나이를 입력하시오: '))
height = int(input('키를 입력하시오: '))

if age >= 40:
    if height >= 170:
        print('키가 보통 이상 입니다.')
    else:
        print('키가 보통입니다.')
else:
    if height >= 175:
        print('키가 보통 이상 입니다.')
    else:
        print('키가 보통입니다.')


# #### if ~ elif ~ 구문

# In[ ]:


score = int(input('총점을 입력해 주세요: '))

if score >= 90:
    print('수')
else:
    if 80 <= score < 90:
        print('우')
    else:
        if 70 <= score < 80:
            print('미')
        else:
            if 60 <= score < 70:
                print('양')
            else:
                print('가')
       


# In[ ]:


score = int(input('총점을 입력해 주세요: '))

if score >= 90:
    print('수')
elif 80 <= score < 90:
    print('우')
elif 70 <= score < 80:
    print('미')
elif 60 <= score < 70:
    print('양')
else:
    print('가')
       


# #### 조건부 표현식 ( 3항 연산자 )

# In[ ]:


score = int(input('총점을 입력해 주세요: '))

if score >= 60:
    message = "success"
else:
    message = "failure"
   
print(message)


# In[ ]:


score = int(input('총점을 입력해 주세요: '))

message = "success" if score >= 60 else "failure"

print(message)


# In[ ]:


score = int(input('총점을 입력해 주세요: '))

message = "A+" if score >= 90 else 'A0' if score >= 80 else "B+"

print(message)


# ### 2.3 반복 흐름과  for, while 문

# #### for 문

# In[ ]:


message = 'Hello!'
messages = ['Hello World', '서울과학종합대학원 빅데이터MABA']
numbers = (1,2,3)
polygon = {'triangle': 2, 'rectangle': 3, 'line': 1}
color = {'red', 'green', 'blue'}

for item in message:
    print(item)

print()

for item in messages:
    print(item)

print()

for item in numbers:
    print(item)

print()

for item in polygon:
    print(item)

print()

for item in color:
    print(item)


# In[ ]:


total = 0

for item in [1,2,3,4,5,6,7,8,9,10]:
    total = total + item
   
print('1부터 10까지 합은 ', total, ' 입니다.')


# #### range() 함수

# In[ ]:


total = 0

for item in range(1,11):
    total = total + item
   
print('1부터 10까지 합은 ', total, ' 입니다.')


# In[ ]:


total = 0

for item in range(1,101):
    total = total + item
   
print('1부터 100까지 합은 ', total, ' 입니다.')


# In[ ]:


total = 0

for item in range(0,101,2):
    total = total + item
   
print('1부터 100까지 짝수 합은 ', total, ' 입니다.')


# In[ ]:


total = 0

for item in range(1,101):
    if (item % 3) == 0 or (item % 7) == 0:
        total = total + item
   
print('1부터 100까지에서 3 혹은 7의 배수의 합은 ', total, ' 입니다.')


# In[ ]:


total = 0

for item in range(1,101):
    total = total + item
else:
    print('덧셈 작업이 끝났습니다.')
   
print('1부터 100까지 합은 ', total, ' 입니다.')


# In[ ]:


for i in range(3, 5):

    print('--{}단 시작--'.format(i))
   
    for j in range(1, 10):
   
        print(i, "*", j, "=", i * j)


# #### 리스트 내포(List comprehension)

# In[ ]:


lst = [1,2,3,4]

result = []
for num in lst:
    result.append(num*3)

print(result)


# In[ ]:


# list comprehension

lst = [1,2,3,4]
result = [num * 3 for num in lst]

print(result)


# In[ ]:


# list comprehension with if

lst = [1,2,3,4]
result = [num * 3 for num in lst if num % 2 == 0]

print(result)


# #### while 문

# In[ ]:


count = 1

while count <= 10:
    print(count)
    count = count + 1


# In[ ]:


count = 1
total = 0

while count <= 100:
    total = total + count
    count = count + 1

print('1부터 100까지의 합은:', total )


# In[ ]:


count  = 1
result = 0

while count <= 100:
    result = result + count
    count  = count + 1
else:
    print('덧셈이 작업 완료 되었습니다.')

print('1부터 100까지의 합은:', result )


# ### 2.4 break 문과 continue 문

# In[ ]:


break_letter = input('중단할 문자를 입력하시오: ')

for letter in 'python':
    if letter == break_letter:
        break
    print(letter)
   
else:
    print('모든 문자 출력 완료!')


# In[ ]:


continue_letter = input('건너뛸 문자를 입력하시오: ')

for letter in 'python':
    if letter == continue_letter:
        continue
    print(letter)
   


# ### 2.5 pass 문

# In[ ]:


input_letter = input('중단할 문자를 입력하시오: ')

for letter in 'python':
    if letter == input_letter:
        pass
    print(letter)
   


# ### 2.6 무한 반복

# In[ ]:


choice = None

while True:
    print('1. 원 그리기')
    print('2. 사각형 그리기')
    print('3. 선 그리기')
    print('4. 종료')
   
    choice = input('메뉴를 선택하시오: ')
   
    if choice == '1':
        print('원 그리기를 선택했습니다.')
    elif choice == '2':
        print('사각형 그리기를 선택했습니다.')
    elif choice == '3':
        print('선 그리기를 선택했습니다.')
    elif choice == '4':
        print('종료합니다.')
        break
    else:
        print('잘못된 선택을 했습니다.')


# ### 2.7 예제: 요일 구하기

# 1. 서기 1년 1월 1일은 월요일이다.  
# <br>
# 1. 윤년을 구하는 공식은 다음과 같다.
#   - 4로 나누어지는 해는 윤년이다.
#   - 100으로 나누어지는 해는 윤년이 아니다.
#   - 400으로 나누어지는 해는 윤년이다.

# In[ ]:


# 년월일을 입력 받는다.
year  = int(input('년도를 입력하시오: '))
month = int(input('월을 입력하시오: '))
day   = int(input('일을 입력하시오: '))

total_days = 0

# 달별 날수를 리스트로 저장
year_month_days = [0,31,28,31,30,31,30,31,31,30,31,30,31]


# 서기 1년부터 year-1 까지의 각 년도 별 날수를 합한다.
for item in range(1, year):
    if item % 400 == 0:                 # 400으로 나뉘는 해: 윤년
        total_days = total_days + 366
    elif item % 100 == 0:               # 100으로 나뉘는 해: 평년
        total_days = total_days + 365
    elif item % 4 == 0:                 # 4으로 나뉘는 해  : 윤년
        total_days = total_days + 366
    else:
        total_days = total_days + 365


# 1월 달부터 month-1 까지의 각 달의 날수를 합한다.
for item in range(1, month):
    total_days = total_days + year_month_days[item]
   

# 입력된 달이 3이상이고 해당년도가 윤년일 경우 1을 추가
if month >= 3:
    if year % 400 == 0:                 # 400으로 나뉘는 해: 윤년
        total_days = total_days + 1
    elif year % 100 == 0:               # 100으로 나뉘는 해: 평년
        total_days = total_days + 0
    elif year % 4 == 0:                 # 4으로 나뉘는 해  : 윤년
        total_days = total_days + 1
    else:
        total_days = total_days + 0


total_days += day

# 총 날수를 7로 나눈 나머지를 구한다.
remainder = total_days % 7

if remainder == 0:
    print('일요일 입니다.')
elif remainder == 1:
    print('월요일 입니다.')
elif remainder == 2:
    print('화요일 입니다.')
elif remainder == 3:
    print('수요일 입니다.')
elif remainder == 4:
    print('목요일 입니다.')
elif remainder == 5:
    print('금요일 입니다.')
elif remainder == 6:
    print('토요일 입니다.')


# ### 2.8 예제: 성적 처리 시스템

# In[ ]:


# 학생 데이터 초기화
students = [
               {'num':'1','name':'김철수','kor':90,'eng':80,'math':85,'total':0,'avg':0.0,'order':0 },
               {'num':'2','name':'박제동','kor':90,'eng':85,'math':90,'total':0,'avg':0.0,'order':0 },
               {'num':'3','name':'홍길동','kor':80,'eng':80,'math':80,'total':0,'avg':0.0,'order':0 }
           ]


# 반 총점, 평균 및 각 과목별 총점과 평균 초기화
class_total = 0
class_avg   = 0.0
kor_total   = 0
kor_avg     = 0.0
eng_total   = 0
eng_avg     = 0.0
math_total  = 0
math_avg    = 0.0


# 학생들의 성적 총점과 평균 및 반 총점과 과목별 총점을 구한다.
for student in students:
    student['total'] = student['kor'] + student['eng'] + student['math']
    student['avg']   = student['total'] / 3
   
    class_total = class_total + student['total']
    kor_total   = kor_total   + student['kor']
    eng_total   = eng_total   + student['eng']
    math_total  = math_total  + student['math']

class_avg = class_total / len(students)
kor_avg   = kor_total   / len(students)
eng_avg   = eng_total   / len(students)
math_avg  = math_total  / len(students)


# 학생별 성적 처리 결과를 출력한다.
for student in students:
    print('번호: {:s}, 이름: {:s}, 국어: {:d}, 영어: {:d}, 수학: {:d}, 총점: {:d}, 평균: {:.2f}'.format(
           student['num'], student['name'],
           student['kor'], student['eng'], student['math'],
           student['total'], student['avg'])
         )
print()


# 반 평균 및 각 과목별 평균을 출력한다.
print('반 평균  : {:.2f}'.format(class_avg))
print('국어 평균: {:.2f}'.format(kor_avg)  )
print('영어 평균: {:.2f}'.format(eng_avg)  )
print('수학 평균: {:.2f}'.format(math_avg) )


# ### 2.9 예제: 모스부호

# In[ ]:


# 모스부호
dic = {
    '.-': 'A', '-...': 'B', '-.-.': 'C', '-..': 'D', '.':'E', '..-.': 'F',
    '--.': 'G', '....': 'H', '..': 'I', '.---': 'J', '-.-': 'K', '.-..': 'L',
    '--': 'M', '-.': 'N', '---': 'O', '.--.': 'P', '--.-': 'Q', '.-.': 'R',
    '...': 'S', '-': 'T', '..-': 'U', '...-': 'V', '.--': 'W', '-..-': 'X',
    '-.--': 'Y', '--..': 'Z'
}
 
# 풀어야할 암호: HE SLEEPS EARLY
code = '.... .  ... .-.. . . .--. ...  . .- .-. .-.. -.--'


# In[ ]:


for word in code.split("  "):
    for char in word.split():
        print(dic.get(char), end='')
    print(" ", end='')


# ### 2.10 예제: 게시글 제목 추출

# In[ ]:


# 게시글 제목
title = """On top of the world! Life is so fantastic if you just let it.
I have never been happier. #nyc #newyork #vacation #traveling"""

tag_list = []
for tag in title.split(" "):
    if tag.startswith("#"):
        tag_list.append(tag[1:])

print(tag_list)


# ---

# # 기타

# ### enumerate()

# In[ ]:


some_list = ['foo', 'bar', 'baz']
for i, v in enumerate(some_list):
    print('i: {}, v: {}'.format(i,v))


# ### zip()

# In[ ]:


seq1 = ['foo', 'bar', 'baz']
seq2 = ['one', 'two', 'three']

for a, b in zip(seq1, seq2):
    print('a: {}, b: {}'.format(a, b))


# ### 리스트, 사전 내포(comprehension)

# In[ ]:


strings = ['a', 'as', 'bat', 'car', 'dove', 'python']


# In[ ]:


# list
lst = [x.upper() for x in strings if len(x) > 2]
lst


# In[ ]:


# dict
dic = {key: index for index, key in enumerate(strings)}
dic


# ---

# In[ ]:


# end of file


# In[ ]:





반응형
LIST