Search
🔺

3. 조건문

CHAPTER 3-9. Conditional Statement(IF)

두 개를 출력하는 경우
if-elif-else말고 nested 구조를 이용해 작성

CHAPTER 3-10. Iteration Statement(while)

1. while?

조건을 만족할 때 까지 반복함
→ 몇번 돌라고 말하지 않고, 조건을 기준으로 조건이 만족될 때 까지 반복함
예제
# 자판기의 커피 수량 coffee = 5 #커피가 0이 되기 전까지 while coffee > 0 money = int(input("금액을 입력해주세요 : ")) if money == 300: # 실제로 이 파트는 자판기에서 커피를 뽑는 명령으로 대체된다. print("Coffee") # 이제 커피를 하나씩 줄인다. coffee = coffee - 1 # coffee -= 1 elif money < 300: # 실제로 이 파트는 돈을 반환한다. print("%d원을 돌려줍니다." % money) else: # or elif money > 300: print("Coffee") # 커피를 뽑아주고 coffee = coffee - 1 # 이제 커피를 하나씩 줄인다. print("%d원을 돌려줍니다." % (money - 300)) # 거스름돈을 돌려준다. # 커피가 다 떨어진 경우 알려야한다. print("커피가 모두 소진되었으니, 관리자에게 문의해주세요.")
JavaScript
복사

CHAPTER 3-11. Conditional Statement(for)

01. Break와 Continue

break : 반복문을 수행하다가 더 이상 반복이 필요없는 경우. 그만해!
continue: 반복문을 수행하다가 특정 조건에만 건너뛰는 경우. 넘어가!
→ countinue를 만나면 밑에로 내려가지 않고 다시 위로 올라감

02. 예제

예제 1
# 자판기의 커피 수량 coffee = 5 # 거스름돈 보관 money = 0 # 일단 작동! while coffee > 0: money = int(input("금액을 입력해주세요:")) money = money + extra_money if money == 300: print("Coffee") coffee = coffee - 1 elif money < 300: print(f"{300-money}만큼의 돈을 더 주세요.") extra_money = money continue else: print("Coffee") coffee = coffee - 1 print("%d원을 반환합니다." % (money-300)) print("커피가 모두 소진되었으니, 관리자에게 문의해주세요.")
JavaScript
복사
예제2
coffee = 5 extra_money = 0 while coffee > 0: money = int(input("금액을 입력해주세요:")) money = money + extra_money #처음엔 extra_money가 0이었으니까, money- = money 아무의미가 없음 #두번째 money<300에 걸렸을때 m받은 money가 extra_money에 들어간 상태로 올라오게 되는데, if money == 300: coffee = coffee - 1 print("Coffee",f"남은 커피는 {coffee}개 입니다.") elif money < 300: print(f"{300-money}만큼 더 필요합니다. 추가로 돈을 입력해주세요.") extra_money = money continue elif money > 300: coffee = coffee - 1 print(f"{money-300}원을 거슬러 드릴게요. 이제 남은 커피는 {coffee}개 입니다.") extra_money = 0 #extra_money에 저장된 돈을 0으로 만들어야 하니까 print("커피가 모두 소진되었으니, 관리자에게 문의해주세요.")
Python
복사

CHAPTER 3-12. Programming Practice(if, while, for)

1. 약수찾기

문제
[ ] 중가로 안에 한 줄로 쓰게 되면 리스트처럼 값이 나옴
기존에 쓰던것처럼 :로 나누어 쓰게되면 숫자들이 세로로 쭉 나옴
# 문제2의 코드를 작성하세요. print([x for x in range(1, 101) if x % 5 == 0])
Python
복사

2. 단어 갯수 구하기

문제
#아래 5개의 변수들은 각각 하나의 문서를 의미합니다. news1 = "earn champion products ch approves stock split champion products inc said its board of directors approved a two for one stock split of its common shares for shareholders of record as of april the company also said its board voted to recommend to shareholders at the annual meeting april an increase in the authorized capital stock from five mln to mln shares reuter" news2 = "acq computer terminal systems cpml completes sale computer terminal systems inc said it has completed the sale of shares of its common stock and warrants to acquire an additional one mln shares to sedio n v of lugano switzerland for dlrs the company said the warrants are exercisable for five years at a purchase price of dlrs per share computer terminal said sedio also has the right to buy additional shares and increase its total holdings up to pct of the computer terminal s outstanding common stock under certain circumstances involving change of control at the company the company said if the conditions occur the warrants would be exercisable at a price equal to pct of its common stock s market price at the time not to exceed dlrs per share computer terminal also said it sold the technolgy rights to its dot matrix impact technology including any future improvements to woodco inc of houston tex for dlrs but it said it would continue to be the exclusive worldwide licensee of the technology for woodco the company said the moves were part of its reorganization plan and would help pay current operation costs and ensure product delivery computer terminal makes computer generated labels forms tags and ticket printers and terminals reuter" news3 = "earn cobanco inc cbco year net shr cts vs dlrs net vs assets mln vs mln deposits mln vs mln loans mln vs mln note th qtr not available year includes extraordinary gain from tax carry forward of dlrs or five cts per shr reuter" news4 = "earn am international inc am nd qtr jan oper shr loss two cts vs profit seven cts oper shr profit vs profit revs mln vs mln avg shrs mln vs mln six mths oper shr profit nil vs profit cts oper net profit vs profit revs mln vs mln avg shrs mln vs mln note per shr calculated after payment of preferred dividends results exclude credits of or four cts and or nine cts for qtr and six mths vs or six cts and or cts for prior periods from operating loss carryforwards reuter" news5 = "earn brown forman inc bfd th qtr net shr one dlr vs cts net mln vs mln revs mln vs mln nine mths shr dlrs vs dlrs net mln vs mln revs billion vs mln reuter"
Python
복사
내 풀이/답
news_list = news1.split() + news2.split() + news3.split() + news4.split() + news5.split() word_Dict = {} for word in news_list: word_Dict[word] = news_list.count(word) print(word_Dict)
Python
복사