Skip to content

Latest commit

 

History

History
185 lines (136 loc) · 3.2 KB

File metadata and controls

185 lines (136 loc) · 3.2 KB

제어문

if문

money = True
if money:
  print("택시를 타고 가라")
else:
  print("걸어 가라")
x = 3
y = 2
x > y
x < y
x == y
x != y
money = 2000
if money >= 3000:
  print("택시를 타고 가라")
else:
  print("걸어 가라")
pocket = ['paper', 'cellphone']
card = True
if 'money' in pocket:
  print("택시를 타고 가라")
elif card:
  print("택시를 타고 가라")
else:
  print("걸어 가라")

while문

while문은 조건문이 참인 동안에 while문 아래의 문장이 반복해서 수행된다.

treeHit = 0
while treeHit < 10:
  treeHit = treeHit + 1
  print("나무를 %d번 찍었습니다." % treeHit)
  if treeHit == 10:
    print("나무 넘어갑니다.")
coffee = 10
money = 300
while money:
  print("돈을 받았으니 커피를 줍니다.")
  coffee = coffee - 1
  print("남은 커피의 양은 %d개입니다." % coffee)
  if coffee == 0:
    print("커피가 다 떨어졌습니다. 판매를 중지합니다.")
    break

coffee.py

coffee = 10
while True:
  money = int(input("돈을 넣어 주세요: "))
  if money == 300:
    print("커피를 줍니다.")
    coffee = coffee - 1
  elif money > 300:
    print("거스름돈 %d를 주고 커피를 줍니다." % (money - 300))
    coffee = coffee - 1
  else:
    print("돈을 다시 돌려주고 커피를 주지 않습니다.")
    print("남은 커피의 양은 %d개 입니다." % coffee)
  if coffee == 0:
    print("커피가 다 떨어졌습니다. 판매를 중지 합니다.")
    break

for문

test_list = ['one','two','three']
for i in test_list:
  print(i)
a = [(1,2), (3,4), (5,6)]
for (first, last) in a:
  print(first + last)

총 5명의 학생이 시험을 보았는데 시험 점수가 60점이 넘으면 합격이고 그렇지 않으면 불합격이다. 결과 보여주기

marks = [90, 25, 67, 45, 80]
number = 0
for mark in marks:
  number = number +1
  if mark >= 60:
    print("%d번 학생은 합격입니다." % number)
  else:
    print("%d번 학생은 불합격입니다." % number)

for문과 continue

marks = [90, 25, 67, 45, 80]

number = 0
for mark in marks:
  number = number + 1
  if mark < 60:
    continue
  print("%d번 학생 축하합니다. 합격입니다." % number)

점수가 60점 이하인 학생일 경우에는 mart < 60 이 참이 되어 continue문이 수행된다. 따라서 축하 메세지를 출력하는 부분인 print문을 수행하지 않고 for문의 처음으로 돌아가게 된다

for문과 함께 자주 사용하는 range 함수

add = 0
for i in range(1,11):
  add = add + i

print(add)

range(1,11)은 숫자 1부터 10까지(1이상 11미만)의 숫자를 데이터로 갖는 객체이다. 따라서 1~10까지 숫자만 반복적으로 수행

marks = [90, 25, 67, 45, 80]
for number in range(len(marks)):
  if marks[number] < 60:
    continue
  print("%d번 학생 축하합니다. 합격입니다." % (number+1))
a = [1,2,3,4]
result = []
for num in a:
  result.append(num*3)
print(result)