■ while문
문장을 반복해서 수행해야 할 경우 while문을 사용한다. 그래서 while문을 반복문이라고도 부른다.
ex. 나무를 10번까지 찍으면 끝난다.
>>> treeHit = 0
>>> while treeHit < 10:
treeHit = treeHit + 1
print("i hit %d times." % treeHit)
if treeHit == 10:
print("finish!")
i hit 1 times.
i hit 2 times.
i hit 3 times.
i hit 4 times.
i hit 5 times.
i hit 6 times.
i hit 7 times.
i hit 8 times.
i hit 9 times.
i hit 10 times.
finish!
ex. 간단한 커피자판기
>>> coffee = 10
>>> money = 300
>>> while money:
print("here you are")
coffee = coffee - 1
print("we have %d coffee." % coffee)
if coffee == 0:
print("sold out")
break
here you are
we have 9 coffee
here you are
we have 8 coffee
here you are
we have 7 coffee
here you are
we have 6 coffee
here you are
we have 5 coffee
here you are
we have 4 coffee
here you are
we have 3 coffee
here you are
we have 2 coffee
here you are
we have 1 coffee
here you are
we have 0 coffee
sold out
ex. 실제 커피자판기 (금액 : 300원, 커피 잔량 : 10잔)
>>> coffee = 10
>>> while True:
money = int(input("insert money"))
if money == 300:
print("here you are")
coffee = coffee - 1
elif money > 300:
print("keep the change %d, here you are" % (money - 300))
coffee = coffee - 1
else:
print("return money")
print("we have %d coffee." % coffee)
if coffee == 0:
print("sold out")
break
insert money["숫자 삽입"]
- 300 입력하면?
here you are
- 300 이상 입력하면?
keep the change 00, here you are
- 300 이하 입력하면?
return money['거스름돈']
we have 00 coffee.
- 10잔 다 팔리면?
sold out
'Python > 파이썬 기초' 카테고리의 다른 글
[1-1] 변수 (0) | 2024.06.29 |
---|---|
[3-3] for문 (0) | 2024.06.29 |
[3-1] if문 (0) | 2024.06.29 |
[2-7] 불 자료형 (0) | 2024.06.28 |
[2-6] 집합 자료형 (0) | 2024.06.28 |