2. Condition Loop

in kr •  6 years ago 

python-logo.png

2. Condition Loop

파이썬의 입력(input), 출력(print), 조건(if, elif, else), 반복(while, for, comprehension)에 대해서 학습합니다.

  1. 입력 : Input
  2. 출력 : Print
  3. 조건 : Condition
  4. 반복 : Loop

1. 입력 : Input

1.1 문자열 입력

코드

value = input("insert string : ")
print(type(value), value)

결과

insert string : dss
<class 'str'> dss

1.2 숫자 입력

  • input을 이용하여 받은 입력은 string 데이터 타입이기 때문에 숫자로 입력 받기 위해서는 형변환을 해줘야 합니다.

코드

value = int(input("insert number : "))
print(type(value), value)

결과

insert number : 5
<class 'int'> 5

1.3 입력 값 활용

  • 공백으로 여러개의 값 입력

코드

value = input("insert string : ")
value = value.split(" ")
print(type(value), value)

결과

insert string : a b c
<class 'list'> ['a', 'b', 'c']
  • 반복문으로 여러번 값을 입력 받음

코드

ls = []
for _ in range(3):
    ls.append(input("insert string : "))
ls

결과

insert string : a
insert string : b
insert string : c
['a', 'b', 'c']
  • 입력 받은 숫자를 반복문에 활용

코드

n = int(input("number : "))
for _ in range(n):
    print("dss")

결과

number : 3
dss
dss
dss

2. 출력 : Print

2.1 Print

2.1.1 여러개의 값을 출력

print("fast", "campus")

2.1.2 sep 파라미터

  • sep 파라미터는 sep=" "으로 설정되어 있습니다.
print("fast", "campus", sep="@")

2.1.3 end 파라미터

  • end 파라미터는 end="\n"으로 설정되어 있습니다.
print("fast", end="\t")
print("campus")
print("fast", end=" ")
print("campus")

2.1.4 string format 사용

  • 순서를 맞춰줘야 합니다.
a, b = 1234, "fastcampus"
print("number : {}, string: {}".format(a, b))
  • 키워드로 매핑을 시키기 때문에 순서가 맞지 않아도 됩니다.
a, b = 1234, "fastcampus"
print("number : {num}, string: {string}".format(num=a, string=b))
a, b = 1234, "fastcampus"
print("number : {num}, string: {string}".format(string=b, num=a))
  • 문자열 사이에 + 연산자를 사용하여 문자열을 만들어 줄수도 있습니다.
print("number : " + str(a) + ", string: " + b)

2.2 pprint

  • 가독성을 위해 줄바꿈으로 정렬하여 출력합니다.

코드

dic = {"A":90, "B":70, "C":100, "D":90, "E":70, "F":100, "G":90, "H":70, "I":100}
print(dic)

결과

{'A': 90, 'B': 70, 'C': 100, 'D': 90, 'E': 70, 'F': 100, 'G': 90, 'H': 70, 'I': 100}

코드

from pprint import pprint
pprint(dic)

결과

{'A': 90,
 'B': 70,
 'C': 100,
 'D': 90,
 'E': 70,
 'F': 100,
 'G': 90,
 'H': 70,
 'I': 100}

3. 조건 : Condition

  1. if
  2. else
  3. elif

3.1 if

  • condition이 True이면 code_1이 실행 됩니다.
if <condition>:
    <code_1>

코드

state = True
if state:
    print("if")

결과

if

코드

state = False
if state:
    print("if")
print("end")

결과

end

3.2 else

  • condition이 False이면 code_2 가 실행됩니다.
if <condition>:
    <code_1>
else:
    <code_2>

코드

state = False
if state:
    print("if")
else:
    print("else")

결과

else

3.3 elif

condition_1이 False이면 condition_2를 확인하여 condition_2가 True이면 code_2 가 실행됩니다.

if <condition_1>:
    <code_1>
elif <condition_2>:
    <code_2>
else:
    <code_3>
  • 비교 연산자 사용

코드

a, b = 30, 30
if a < b:
    print("a < b")
elif a == b:
    print("a == b")
else:
    print("a > b")

결과

a == b

코드

if a < b:
    print("a < b")
elif a == b:
    print("a == b")

결과

a == b

코드

a, b = 30, 30
if a < b:
    print("a < b")
if a == b:
    print("a == b")
if a > b:
    print("a > b")

결과

a == b
  • 논리 연산자 사용

코드

a, b = 10, 20
if a < 20 and b < 10:
    print("code 1")
else:
    print("code 2")

결과

code 2
Quiz 1
  • 숫자를 입력받아 짝수이면 even, 홀수이면 odd를 출력하는 코드를 작성하세요.
number = int(input("insert number : "))
if number <= 0:
    print("error")
elif number % 2 == 0:
    print("even")
else:
    print("odd")
Quiz 2
  • 숫자을 입력받아 3의 배수이면 fizz, 5의 배수이면 buzz, 3과 5의 배수이면 fizzbuzz를 출력하고 3과 5의 배수가 아니면 입력한 숫자를 출력하는 코드를 작성하세요.
number = int(input("insert number : "))

if number % 15 == 0:
    print("fizzbuzz")
elif number % 3 == 0:
    print("fizz")
elif number % 5 == 0:
    print("buzz")
else:
    print(number)
number = int(input("insert number : "))

if number % 3 == 0:
    print("fizz", end="")
if number % 5 == 0:
    print("buzz")
if not( (number % 3 == 0) or (number % 5 == 0)):
    print(number)

3.3 삼항연산

  • condition이 True이면 A를 리턴하고 condition이 False이면 B를 리턴합니다.
A if (condition) else B

코드

a = 0
if a:
    print(1)
else:
    print(2)

결과

2

코드

a = 0
True if a else False

결과

Fasle

코드

a = 1
True if a else False

결과

True
  • 1: 남자, 2: 여자를 출력하는 코드

코드

b = 1
"male" if b == 1 else "female"

결과

male

코드

b = 2
result = "male" if b == 1 else "female"
result

결과

female
Quiz 3
  • 삼항연산을 이용하여 값을 입력받아 짝수이면 even, 홀수이면 odd를 출력하는 코드를 작성하세요.
number = int(input("insert number : "))

result = "even" if number % 2 == 0 else "odd"
result

4.반복 : Loop

  1. while
  2. break
  3. continue
  4. for
  5. list comprehension

4.1 while

  • condition이 True이면 while 안쪽의 code가 실행 후 다시 condition을 확인하여 True이면 code를 실행을 반복합니다.
while <condition>:
    <code>

* while 은 잘못사용하면 무한루프에 빠지기 때문에 주의해서 사용해야 합니다.

코드

a = 3
while a:
    print(a)
    a -= 1
a

결과

3
2
1
0

4.2 break

  • 반복문이 실행되던 중간에 break를 만나게 되면 반복문이 종료됩니다.

코드

a = 3
while a:
    print(a)
    if a == 2:
        break
    a -= 1
a

결과

3
2
2

4.3 continue

  • 반복문이 실행되던 중간에 countinue를 만나게 되면 반복문 구문의 최상단으로 올라가서 코드가 수행됩니다.

코드

a = [1, 2, 3, 4, "q"]
idx = 0

while True:
    data = a[idx]
    idx += 1

    if data == 'q':
        break
    elif data % 2 == 0:
        continue

    print(data)

idx

결과

1
3
5
Quiz 4
  • q를 입력할때 까지 계속 값을 입력받아 입력받은 값을 q를 입력할때 리스트로 출력하는 코드를 작성하세요. 입력 데이터를 받을때는 몇번째 입력인지 출력해주세요.
1번째 입력 (종료 : q) : dss
2번째 입력 (종료 : q) : data
3번째 입력 (종료 : q) : science
4번째 입력 (종료 : q) : q
['dss', 'data', 'science']
# TODO - input, print, list, if, while, 비교연산자

count, result = 1, []

while True:

    data = input("{}번째 입력 (종료 : q) : ".format(count))
    count += 1

    if data == "q":
        print(result)
        break

    result.append(data)

결과

1번째 입력 (종료 : q) : dss
2번째 입력 (종료 : q) : data
3번째 입력 (종료 : q) : science
4번째 입력 (종료 : q) : qwer
5번째 입력 (종료 : q) : q
['dss', 'data', 'science', 'qwer']

4.4 for

  • iterable의 데이터를 하나씩 꺼내서 value에 대입시킨후 code를 수행합니다. code는 iteralbe의 갯수 만큼 실행됩니다.
for <value> in <iterable> :
    <code>
  1. range
  2. enumerate
  3. zip

코드

ls = [0, 1, 2, 3, 4]
for value in ls:
    print(value, end=" ")

결과

0 1 2 3 4

코드

ls = ["a","b","c", [1,2]]
for value in ls:
    print(value, type(value))

결과

a <class 'str'>
b <class 'str'>
c <class 'str'>
[1, 2] <class 'list'>
  • dictionary에서 반복문을 사용할때는 items 함수를 사용해야 key, value 값을 모두 가져올수 있습니다.

코드

dic = {"A": 1, "B": 2}
for key in dic:
    print(key)

결과

A
B

코드

dic.items()

결과

dict_items([('A', 1), ('B', 2)])

코드

for key, value in dic.items():
    print(key, value)

결과

A 1
B 2
Quiz 5
  • for문을 이용하여 아래 리스트에 있는 숫자를 모두 더하는 코드를 작성하세요.
numbers = [1, 3, 5, 8, 10, 14]
result : 41
sum(numbers)

4.4.1 range

  • list를 간편하게 생성하기 위한 함수입니다.
range(end)
range(start, end)
range(start, end, stride)

코드

ls = [0, 1, 2, 3, 4]
print(ls)
for _ in ls:
    print("dss")

결과

[0, 1, 2, 3, 4]
dss
dss
dss
dss
dss

코드

# range(end)
list(range(5))

결과

[0, 1, 2, 3, 4]

코드

# range(end)
for value in range(5):
    print(value, type(value))

결과

0 <class 'int'>
1 <class 'int'>
2 <class 'int'>
3 <class 'int'>
4 <class 'int'>
  • range(start, end)

코드

list(range(2, 5))

결과

[2, 3, 4]
  • range(start, end, stride)

코드

list(range(1, 10, 2))

결과

[1, 3, 5, 7, 9]

코드

list(range(10, 1, -1))

결과

[10, 9, 8, 7, 6, 5, 4, 3, 2]

코드

a = 0
for _ in range(5):
    a += 1
a

결과

5
Quiz 6
  • 구구단을 4단까지 세로로 출력하는 코드를 작성하세요.
2단
2*1=2
2*2=4
2*3=6
2*4=8
2*5=10
2*6=12
2*7=14
2*8=16
2*9=18

3단
3*1=3
3*2=6
3*3=9
3*4=12
3*5=15
3*6=18
3*7=21
3*8=24
3*9=27

4단
4*1=4
4*2=8
4*3=12
4*4=16
4*5=20
4*6=24
4*7=28
4*8=32
4*9=36
# TODO - 2중 for문
for num1 in range(2, 5):
    print("{}단".format(num1))
    for num2 in range(1, 10):
        print("{}*{}={}".format(num1, num2, num1*num2))
    print()
Quiz 7
  • 구구단을 가로로 출력하는 코드를 작성하세요.
2*1=2   3*1=3   4*1=4   5*1=5   6*1=6   7*1=7   8*1=8   9*1=9
2*2=4   3*2=6   4*2=8   5*2=10  6*2=12  7*2=14  8*2=16  9*2=18
2*3=6   3*3=9   4*3=12  5*3=15  6*3=18  7*3=21  8*3=24  9*3=27
2*4=8   3*4=12  4*4=16  5*4=20  6*4=24  7*4=28  8*4=32  9*4=36
2*5=10  3*5=15  4*5=20  5*5=25  6*5=30  7*5=35  8*5=40  9*5=45
2*6=12  3*6=18  4*6=24  5*6=30  6*6=36  7*6=42  8*6=48  9*6=54
2*7=14  3*7=21  4*7=28  5*7=35  6*7=42  7*7=49  8*7=56  9*7=63
2*8=16  3*8=24  4*8=32  5*8=40  6*8=48  7*8=56  8*8=64  9*8=72
2*9=18  3*9=27  4*9=36  5*9=45  6*9=54  7*9=63  8*9=72  9*9=81
# TODO - 2중 for문, print(end)
for num2 in range(1, 10):
    for num1 in range(2, 10):
        print("{}*{}={}".format(num1, num2, num1*num2), end="\t")
    print()
Quiz 8

아래의 2개의 리스트 데이터를

subjects = ["korean", "english", "math", "science"]
points = [100, 80, 90, 60]

아래와 같이 딕셔너리 데이터로 만드는 코드를 작성하세요.

{'english': 80, 'korean': 100, 'math': 90, 'science': 60}
# TODO - list, dictionary, for

subjects = ["korean", "english", "math", "science"]
points = [100, 80, 90]
result = {}

count = len(points) if len(subjects) > len(points) else len(subjects)

for idx in range(count):
    print(subjects[idx], points[idx])
    result[subjects[idx]] = points[idx]

result

4.4.2 enumerate

  • 리스트 데이터를 index와 value값을 동시에 사용할 수 있게 해주는 함수입니다.

  • 과목이름과 과목에 대한 순서를 출력

코드


subjects = ["korean", "english", "math", "science"]
number = 1
for value in subjects:
    print(number, value)
    number += 1

결과

1 korean
2 english
3 math
4 science

코드

subjects = ["korean", "english", "math", "science"]
for idx, value in enumerate(subjects):
    print(idx + 1, value)

결과

1 korean
2 english
3 math
4 science

코드

tuple(enumerate(subjects))

결과

((0, 'korean'), (1, 'english'), (2, 'math'), (3, 'science'))

4.4.3 zip

  • n개의 리스트를 같은 index끼리 묶어주는 함수
  • zip을 이용하여 list를 dictionary로 묶어줍니다.

코드

subjects = ["korean", "english", "math", "science"]
points = [100, 80, 90, 60]
dict(zip(subjects, points))

결과

{'english': 80, 'korean': 100, 'math': 90, 'science': 60}

코드

tuple(zip(subjects, points))

결과

(('korean', 100), ('english', 80), ('math', 90), ('science', 60))

코드

# 3개의 데이터를 묶어줌 : dictionary로 생성되지 않음
grades = ["A","C","B","D"]
tuple(zip(subjects, points, grades))

결과

(('korean', 100, 'A'),
 ('english', 80, 'C'),
 ('math', 90, 'B'),
 ('science', 60, 'D'))

4.5 list comprehension

  • 반복문의 결과를 바로 리스트로 만들어 주는 방법입니다.
  • list 데이터를 만들때 for문 보다 속도가 빠름니다.
ls = [<value> for <value> in <list>]
ls = [<value> for <value> in <list> if <condition>]

4.5.1 기본 사용법

  • 리스트에 1~5까지 숫자를 대입하는 방법

코드

# method 1
ls = []
ls = [1, 2, 3, 4, 5]
print(ls)

# method 2
ls = []
ls.append(1)
ls.append(2)
ls.append(3)
ls.append(4)
ls.append(5)
print(ls)

# method 3
ls = []
for num in range(1,6):
    ls.append(num)
print(ls)

# method 4
ls = []
ls = [num for num in range(1,6)]
print(ls)

결과

[1, 2, 3, 4, 5]
[1, 2, 3, 4, 5]
[1, 2, 3, 4, 5]
[1, 2, 3, 4, 5]

4.5.2 list comprehention과 for문의 속도 비교

%%timeit
# for문 사용
ls = []
for num in range(1,10000):
    ls.append(num)

960 µs ± 16.7 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

%%timeit
# list comprehention 사용
ls = [num for num in range(1,10000)]

354 µs ± 6.34 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

4.5.3 삼항 연산과 함께 사용

  • 1 ~ 10 까지의 숫자를 출력하고 숫자뒤에 짝수인지 홀수 인지 출력하는 코드

코드

ls = [
    str(num) + ":even" if num % 2 == 0 else str(num) + ":odd"
    for num in range(1, 11)
]
ls

결과

['1:odd',
 '2:even',
 '3:odd',
 '4:even',
 '5:odd',
 '6:even',
 '7:odd',
 '8:even',
 '9:odd',
 '10:even']

4.5.4 조건문과 함께 사용

코드

ls = [ number for number in range(1, 11) ]
print(ls)

결과

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
  • 짝수 리스트 만들기

코드

ls = [ number for number in range(1, 11) if number % 2 == 0 ]
print(ls)

결과

[2, 4, 6, 8, 10]
Quiz 9
  • kim 씨 성을 가진 사람은 데이터에서 제거하고, lee 씨 성을 가진사람은 성을 삭제하는 코드를작성하세요
(입력) => ["kim test", "park python", "lee data", "jung science", "lee school"]
(결과) => ["park python", "data", "jung science", "school"]

코드


# TODO - list comprehention, 삼항연산, string.split

names = ["kim test", "park python", "lee data", "jung science", "lee school"]

result = [
    name.split(" ")[1] if name.split(" ")[0] == "lee" else name
    for name in names
    if name.split(" ")[0] != "kim"
]
result

# ["park python", "data", "jung science", "school"]

결과

['park python', 'data', 'jung science', 'school']

* 랜덤함수

import random

# 1 ~ 10 중 하나의 정수가 랜덤하게 출력
random.randint(1, 10)

# 1,5,9 중 하나의 데이터가가 랜덤하게 출력
random.choice([1, 5, 9])
Quiz 10
  • 로또번호를 출력하는 코드를 작성하세요. 1 ~ 45 사이의 숫자를 랜덤으로 뽑되 숫자가 중복되면 안됩니다.
[3, 8, 15, 22, 27, 29]

코드

# TODO - while, break, if, in, list, append

import random

lotto = []

while True:

    number = random.randint(1, 45)

    if number not in lotto:
        lotto.append(number)

    if len(lotto) >= 6:
        lotto.sort()
        break

lotto

결과

[15, 20, 21, 27, 30, 45]
Authors get paid when people like you upvote their post.
If you enjoyed what you read here, create your account today and start earning FREE STEEM!