• Home
  • About
    • Young's Github Pages photo

      一日不作一日不食

    • About
    • Github
  • Posts
    • All Posts
    • All Tags
  • Projects

Python 정리 03

08 May 2019

Reading time ~3 minutes

Python 정리 03 - 제어문


데이터 형에 따른 False 값

  • 조건식을 넣지 않았을 때 False 판정인 경우
    • 객체는 None(null)인 경우 False

01

제어문 - 조건문 if

  • 조건을 부여하고 조건에 맞는 경우 코드를 수행
  • if, if~else, elif로 제공
  • indent로 블록을 구분한다
  • 단일 if
if 조건식 :
    조건에 맞을 때 수행할 문장
# name=input()으로 입력받음
name = input("이름>>")

# 입력받은 이름이 "이재찬"이라면 이름 앞에 "반장"을 출력
if name == "이재찬":
    print("반장")
    
print(name)

02

  • if~else
if 조건식 :
    조건에 맞을 때 수행할 문장
else :
    조건에 맞지 않을 때 수행할 문장
x = None
if x:
    print("데이터형 {}, {} 값 존재".format(type(x), x))
else :
    print("데이텨형 {}, {} 값 존재하지 않음".format(type(x),x))


x = 100
if x:
    print("데이터형 {}, {} 값 존재".format(type(x), x))
else :
    print("데이텨형 {}, {} 값 존재하지 않음".format(type(x),x))


x = 0.1
if x:
    print("데이터형 {}, {} 값 존재".format(type(x), x))
else :
    print("데이텨형 {}, {} 값 존재하지 않음".format(type(x),x))


x = '잡코리아'
if x:
    print("데이터형 {}, {} 값 존재".format(type(x), x))
else :
    print("데이텨형 {}, {} 값 존재하지 않음".format(type(x),x))


x = [1, 2, 3] # list
if x:
    print("데이터형 {}, {} 값 존재".format(type(x), x))
else :
    print("데이텨형 {}, {} 값 존재하지 않음".format(type(x),x))


x = (1, 2, 3) # tuple
if x:
    print("데이터형 {}, {} 값 존재".format(type(x), x))
else :
    print("데이텨형 {}, {} 값 존재하지 않음".format(type(x),x))


x = { 'name':'노진경', 'age':20 }
if x:
    print("데이터형 {}, {} 값 존재".format(type(x), x))
else :
    print("데이텨형 {}, {} 값 존재하지 않음".format(type(x),x))

03

  • else ~ if (다중 if)
if 조건식 : 
    조건에 맞을 때 수행할 문장
elif 조건식 : 
    조건에 맞지 않을 때 수행할 문장
elif 조건식 :
    조건에 맞지 않을 때 수행할 문장
elif 조건식 :
    조건에 맞지 않을 때 수행할 문장
else :
    모든 조건에 맞지 않을 때 수행할 문장
name = input('이름 : ')
star_cnt = 0

if name=='이재찬':
    print('반장')
    star_cnt=5
elif name=='이봉현' or name=='박영민' or name=='오영근':
    print('조장')
    star_cnt=3
elif name=='김정윤':
    print('디잘잘','면잘잘')
    star_cnt=2
else:
    print('평조원')
    star_cnt=1

print(name)
print('★'*star_cnt)

04

제어문 - 반복문 while

  • 인덱스를 사용하지 않고 조건에 맞을 때까지 반복수행
  • indent로 블록 설정
while 조건식 :
    반복수행문장

제어문 - 분기문

  • break, continue
i = 0
while i<10:
    print(i)
    i+=1
    
print('-'*50)

# 분기문 : break
i = 0
while i<10:
    if i==5:
        break
    print(i)
    i+=1

05

제어문 - 반복문 for

  • 인덱스를 사용하여 조건에 맞을 때까지 반복수행
  • List, Tuple, Dictionary를 출력하는 경우
  • index를 사용하는 경우
for 변수명 in range(시작, 끝, 증가) : 
    반복수행할 코드
# 인덱스 사용 range(시작값, 끝값, 증가값)
# 증가값을 사용하지 않으면 1씩 증가
for i in range(1, 10):
    print(i)

06

  • List, Tuple 출력하는 경우
for 변수명 in list명|tuple명 :
    반복수행할 코드
nameList = ['공선의','이재현','최지우','김정윤','박영민']
for name in nameList:
    print(name)

print('-'*30)

nameTuple = ('공선의','이재현','최지우','김정윤','박영민')
for name in nameTuple:
    print(name)

07

  • Dictionary 출력
for k,v in 딕셔너리명.items():
    print("{0} {1}".format(k,v))
langDict = { 'java':'완벽한 OOP언어', 'HTML5':'마크업 언어',
             'CSS':'디자인언어', 'JavaScript':'스크립트 언어',
              'Python':'수치연산에 강한 OOP언어' }

for k,v in langDict.items():
    print('key={}, value={}'.format(k, v))

08

  • 숫자를 거꾸로 출력할 땐 reversed 함수 사용
for i in reversed(range(1,10)):
    print(i)

09

  • 이중 for문은 다음과 같이 사용가능
for i in range(2,9):
    for j in range(1,9):
        print('{}*{}={}'.format(i,j,i*j))

문자열 슬라이싱(Slicing)

  • 입력값 받기 (키보드 입력)
    • java의 System.in.read()와 같음
변수 = input()
변수 = input("보여줄 메시지")

# Slicing, 문자열 자르기
# List, Tuple 자르기
str[시작인덱스:끝인덱스]

str='안녕하세요'
str[0:] # 0번째 인덱스에서 끝까지
str[:끝인덱스] # 처음부터 끝인덱스까지
str[1:3] # '녕하'만 잘리게 됨
str[ : : -1] # reverse, 거꾸로 출력
str = 'ABCDEFG.txt'
#      0123456

print(str)
print(str[0:]) # 시작부터 끝까지
print(str[2:5]) # 특정 위치만 자르기 (CDE)
print(str[:5]) # 시작부터 특정 위치까지만 자르기 (ABCDE)
print(str[::-1]) # 글자 뒤집기
print(str[::2]) #시작부터 특정위치(배수)의 문자만 자르기
print(str[-3:]) # 뒤에서부터 특정 자리의 문자만 자르기

10



Python