파이썬 기초문법 7

지리산근육곰·2021년 8월 10일
0

Python기초문법

목록 보기
7/8
post-thumbnail

8. Control Statement

Control Statement 에서의 조건문

  • 같다 : ==
  • 다르다: !=
  • 크다: >
  • 작다 : <
  • 같거나작다: >=
  • 작거나같다: <=
  • and : A and B
  • or : A or B
  • not : not A # A가 아닌 것

8.1 If Statement (조건문)

  • 특정 조건에 따라 Boolean 값으로 받아 다음 작업에 대한 판단을 한다.

  • 만약 "조건" 이면 무엇을 해라.

  • if 조건 :

    tab

a = 5
# 만약 a 가 5 이면 다음 작업을 하여라
if a == 5:
    print(True)

a = 7

if a == 5:
    print(True)
# 이경우 if에서 조건을 충족 못함으로 아무런 작업도 실행이 안된다.

예시 : 300 원을 집어 넣으면 커피가 나오는 자판기 커피

money = int(input("Input ypur money: "))

if money == 300:
    print("Here is your Coffee")

money = int(input("Input ypur money: "))

if money > 300:
    print("Here is your Coffee and your change %d" %(money-300))

money = int(input("Input ypur money: "))

if money < 300:
    print("Not enough money. Here is your change %d" %(money))

8.2 else and elif

  • 위의 예시 경우 코드를 세 개를 만들어야 한다.
  • 이러한 불편함을 없애기 위해 우리는 else와 elif를 사용한다.
money = int(input("Input ypur money: "))

if money == 300:
    print("Here is your Coffee")
elif money > 300:
    print("Here is your Coffee and your change %d" %(money-300))
else :
    print("Not enough money. Here is your change %d" %(money))

money = int(input("Input Your Money"))

if money >= 300:
    print("Here is your Coffee")
    if money > 300:
        print("Here is your change %d." %(money-300))
else :
    print("Not enough money. Here is your change %d." %(money))

8.3 Interative Statement (반복문)

  • 프로그램에서 가장 중요한 반복이다.

    컴퓨터의 작업은 반복에 최적화 되어있다.

  • 파이썬에서는 while, for 2가지의 statement를 제공한다.

8.3.1 While Statement

  • 특정 조건이 만족될때까지 작업을 반복한다.
  • while (조건):
  • 작업1
  • 작업2
  • 작업 1&2를 조건이 충족되는 한 반복한다.
# 구구단 2단: 입력된 숫자부터 9까지 2단 실행
N = int(input("Input your number"))

while N < 10:
    print("2 X %d = %d" % (N, 2*N))
    N = N+1

자판기 예시: 커피가 있는 수 만큼 팔기

# 팔 수 있는 커피가 5잔 있다. 이때 커피가 다 팔릴 때까지 코드 실행.
coffees = 5

while coffees > 0:
    money = int(input("Input your money: "))

    if money == 300:
        print("Here is your Coffee.")
        coffees = coffees -1

    elif money < 300:
        print("Not enough money. Here is your change %d" % (money))
    
    else:
        print("Here is your Coffee and your change %d" % (money-300))
        coffees = coffees - 1

if coffees == 0:
    print("Sorry. Sold Out.")

8.3.2 for statement

  • for 는 특정 횟수만큼 작업을 실행한다.
L = [1, 2, 3, 4, 5, 6]

for i in L:
    print(i)

coffees = ['아메리카노', '카페라떼', '카페모카', '바닐라라떼', '핸드드립', '콜드브루']

for coffee in coffees:  ## 단수 in 복수형 으로 작성해도 괜찮다.
    print(coffee)

8.3.3 range statement

# range 함수를 이용해 1부터 4까지 출력하는 프로그램을 작성해보자. for문을 이용해서!
range(3) ## 0, 1, 2 !!This is not a list!!
range(1, 5)  ## 1, 2, 3, 4
range(2, 10, 2)  ## 2 이상 부터 10 미만까지 2씩 올린다.

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

for i in range(len(L)):
    print(L[i])

예시1 : 6개의 커피 음료와 음료의 가격이 담긴 리스트가 있다. 가지고 있는 돈이 5,000원일 때 먹을 수 있는 모든 음료를 찾아보자!

coffees = ['아메리카노', '카페라떼', '카페모카', '바닐라라떼', '핸드드립', '콜드브루']
prices = [4100, 4600, 4600, 5100, 6000, 5000]

for i in range(len(coffees)): ## index 0, 1, 2, 3, 4, 5 를 불러온다.
    if prices[i] <= 5000:
        print(coffees[i])

            
print("------")
# enumerate
for i, price in enumerate(prices):
    if price <= 5000:
        print(coffees[i])

print("------")

# zip ## 두개의 리스트가 길이가 같아야 한다.
for coffee, price in zip(coffees, prices):
    if price <= 5000:
        print(coffee)

예시2 : 위의 커피가 500원 할인 되었다. 가지고 있는 돈이 5,000원일 때 먹을 수 있는 모든 음료를 찾아보자!

coffees = ['아메리카노', '카페라떼', '카페모카', '바닐라라떼', '핸드드립', '콜드브루']
prices = [4100, 4600, 4600, 5100, 6000, 5000]

for i in range(len(coffees)):
    if prices[i]-500 <= 5000:
        print(coffees[i])

8.4 break & continue

  • 만약 반복문을 수행하다가 더 이상 반복이 필요없는 경우에는 어떻게 해야할까?

break statement

  • 만약 반복문을 수행하다가 특정 조건에만 건너뛰고 싶은 경우에는 어떻게 해야할까?

continue statement

8.4.1 break

예시: 자판기에서 커피가 sold out 되었을 때 작동이 멈춘다.

  • 5잔의 커피가 sold out 되면 기계가 멈춘다.
  • 300원에 커피를 준다.
  • 돈이 더 들어올 경우 잔돈을 준다.
  • 돈이 300 미만일 경우 돈을 돌려준다.
coffees = 5

while True:    ## 이경우 무한 루프가 된다.
    
    money = int(input("Input your money: "))

    if money == 300:
        print("Here is your Coffee")
        coffees = coffees - 1
    
    elif money < 300:
        print("Here is your change %d" % (money))
    
    else:
        print("Here is your Coffee and change %d" % (money-300))
        coffees = coffees - 1

    if coffees == 0:
        print("Sold out")
        break  ##위에 무한 루프인 while True를 break 한다.

8.4.2 continue

  • 이전 단계의 작업으로 돌아가게 한다.

예시: 자판이에 300원 미만으로 돈이 들어 왔을 시 300원을 넣을 때까지 코드가 실행된다.

coffee = 5

extra_money = 0

while True:

    money = int(input("Input your money: "))

    money = money + extra_money ## 머니를 업데이트 해준다. 

    if money == 300:
        print("Here is your Coffee")
        coffee = coffee - 1
    
    elif money < 300:
        print("Not enough money. Please input more money if you want a Coffee")
        extra_money = money  ## 여기서 업데이트된 extra_money 가 위에 새롭게 들어온 돈에 업데이트 된다.
        continue  ## while 로 돌아 간다.
    
    elif money > 300:
        print("Here is your Coffee and change %d" % (money-300))
        coffee = coffee - 1
    
    if coffee == 0:
        print("Sold out. Sorry for your inconvenience.")
        break

    ##정산 
    extra_money = 0  ## 위에 elif < 300 에서 
       				 ## extra_money에 지정된 값이 있음으로 돈을 0으로 해주어야 한다.

0개의 댓글